[ENet-discuss] ENetHost in two threads
Lee Salzman
lsalzman1 at cox.net
Thu Nov 10 19:18:57 PST 2005
ENet is not currently "thread safe". But, so long as you only have one
thread inside ENet at a time (using some sort of mutex), you will be fine.
Afreet wrote:
> 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
>
>
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> ENet-discuss mailing list
> ENet-discuss at cubik.org
> http://lists.cubik.org/mailman/listinfo/enet-discuss
More information about the ENet-discuss
mailing list