I am writing client in c++ which client get response on two different ports. I am listening to one port in main thread while I have created other thread (posix based) like this:
void *receiveFunc(void *ptr)
{
try {
while ( true ) {
svr_sock << svr_data;
cout<<svr_data<<endl;
}
} catch ( SocketException& ) {}
}
but when it enters into the this thread it never comes out until I have received something on the socket.
How can I overcome this problem?
Your socket is in blocking mode.
It depends on your used OS how to set the socket to non-blocking mode.
Linux: You need to set the socket to nonblocking mode like described in Beej's guide.
Windows: You must use the winsock WinAPI functions.
Why do you need it to 'come out'?
Anyway, the usual way of persuading such a blocked thread to exit is to set some 'terminate' bool for the while loop to check and then close the socket. This causes the socket read to return early with an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With