[ENet-discuss] ENetHost in two threads

Afreet missu at sohu.com
Thu Nov 10 18:20:07 PST 2005


Hi, all.
I am a newbie to Enet library. It is a very powerful tookit for network
transfer layer.

Now I have a question about it. I used a global ENetHost variable in two
threads. Is

this operation thread safe? If not , how do I modify my code? Here is my
sample code:

//in first thread

int Connect(std::string& ip, int port, int timeout) {

ENetAddress address;

         ENetEvent event;

         ENetPeer *enet_peer;

         DWORD addr = inet_addr(ip.c_str());

         HOSTENT* hostnet = gethostbyaddr((const char*)&addr, 4, AF_INET);

         address.host = *(enet_uint32*)hostnet->h_addr_list[0];

         address.port = (unsigned short)port;

         enet_peer = enet_host_connect(_enet_host, &address, 1);

         if ( !enet_peer )

                   return -1;

         if (( enet_host_service(_enet_host, &event, timeout) > 0 ) && 

                   ( event.type == ENET_EVENT_TYPE_CONNECT )) {

                   srand((unsigned)time(NULL));

                   int ID = rand();

                   enet_peer->data = (void*)&ID;

                   return ID;

         }

return -1;

}

//in second thread

//pc is a event observer

while ( _running ) {

         if (enet_host_service(_enet_host, &event, 5000)) {

                  switch( event.type ) {

                           case ENET_EVENT_TYPE_DISCONNECT:

                                     ID = (int)event.peer->data;

                                     pc->OnShutdown(ID);

                                     event.peer->data = NULL;

                                     break;

                            case ENET_EVENT_TYPE_CONNECT:

                                     srand((unsigned int)time(NULL));

                                     ID = rand();

                                     event.peer->data = (void*)&ID;

                                     pc->OnConnect(ID);

                                     break;

                            case ENET_EVENT_TYPE_RECEIVE:

                                     ID = *((int*)event.peer->data);

                                     ce = new ChordEvent;

                                     memcpy(ce, event.packet->data,
event.packet->dataLength);

                                     pc->OnReceive(ce);

                                     break;

                            }

                   }

         }

}

 

  Thank you for your help.

Best wishes,

                                                 Afreet Zhang

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.puremagic.com/pipermail/enet-discuss/attachments/20051111/a24d639d/attachment.htm


More information about the ENet-discuss mailing list