How to let a thread which blocks on recv() exit gracefully? How to let a thread which blocks on recv() exit gracefully? multithreading multithreading

How to let a thread which blocks on recv() exit gracefully?


You can call:-

shutdown(sock, SHUT_RDWR)    //on the remote end

Check this out.


Do not block on recv. Rather implement a block on 'select' and test the input fdset to determine if there is anything to read in the first place.

If there is data to be read, call recv. If not, loop, check 'isrunning' volitile Boolean variable that gets set by the other thread when shutdown has been initiated.


Either:

  1. Set a read timeout, with setsockopt() and SO_RCVTIMEO, and whenever it triggers check a state variable to see if you've told yourself to stop reading.
  2. If you want to stop reading the socket forever, shut it down for input with shutdown(sd, SHUT_RD). This will cause recv() to return zero from now on.
  3. Set the socket into non-blocking mode and use select() with a timeout to tell you when to read, adopting the same strategy with a state variable as at (1) above. However non-blocking mode introduces considerable complications into the send operation, so you should prefer (1) or (2) above.

Your pseudo-code lacks EOS- and error-checking. I hope it doesn't really look like that.