Exiting blocked threads (socket.accept)

Martin Drašar drasar at ics.muni.cz
Wed Mar 27 12:49:53 PDT 2013


Dne 27.3.2013 18:51, Tim napsal(a):
> That works as expected, except the fact that pressing CTRL+C which stops
> the while(!stopServer) doesn't terminate the mainloop in my
> Connection-class (run()-method). This thread is blocked because of the
> receive()-method... but how can I force this thread to exit? Is there
> any chance to do that? I already tried to set the accepted socket to
> blocking(false) without any success...
>
> Thanks in advance for any reply!

Hi Tim,

you have to pass the termination information to the thread. It does not 
know about it and waits for receive() to return.

You will have to employ the select() call to some extent.

1) You can have some form of global variable that indicates termination 
or you can send the termination info using Tid.send(). The code can then 
look like this:

threadSocket.blocking(false);
auto ss = new SocketSet();
while (!shouldEnd)
{
   ss.reset();
   ss.add(threadSocket);

   auto rc = Socket.select(ss, null, null, dur!"msecs"(timeout));
   if (rc == 1)
   {
     // process your data
   }
}

And it would take at most timeout miliseconds for thread to react to 
termination message.

2) Use what Sean Kelly wrote. Either using a pipe or socketpair.

Martin


More information about the Digitalmars-d-learn mailing list