Sockets and multithreading
I have an interesting (for me) problem ... There are two streams, one to grab data from the std input and send it via a socket to the server, and the other to receive data from a blocking socket. So when there is no response from the server, the recv () call waits indefinitely, right? But instead of blocking only the calling thread, it blocks the general process! Why is this happening?
boost::mutex nvtMutex;
boost::mutex strMutex;
boost::mutex quitMutex;
bool quit = false;
void *processServerOutput(void *arg)
{
NVT *nvt = (NVT*)arg;
while(1)
{
// Lock the quitMutex before trying to access to quit variable
quitMutex.lock();
if(quit)
{
quitMutex.unlock();
pthread_exit(NULL);
}
else
quitMutex.unlock();
// Receive output from server
nvtMutex.lock();
nvt->receive();
cout << Util::Instance()->iconv("koi8-r", "utf-8", nvt->getOutBuffer());
nvtMutex.unlock();
// Delay
sleep(1);
}
}
void *processUserInput(void *arg)
{
NVT *nvt = (NVT*)arg;
while(1)
{
// Get user input
//cin.getline(str, 1023);
sleep(3);
strcpy(str, "hello");
// If we type 'quit', exit from thread
if(strcmp(str, "quit") == 0)
{
// Lock quit variable before trying to modify it
quitMutex.lock();
quit = true;
quitMutex.unlock();
// Exit from thread
pthread_exit(NULL);
}
// Send the input to server
nvtMutex.lock();
nvt->writeUserCommand(Util::Instance()->iconv("utf-8", "koi8-r", str));
nvt->send();
nvtMutex.unlock();
}
}
a source to share
You are on hold nvtMutex
inside a call NVT::recv
. Since both threads have to block the mutex in order to iterate through it until NVT::recv
it returns, the other thread cannot progress.
Without knowing the details of this class NVT
, it is impossible to know if you can safely unlock mutexes before calling, NVT::recv
or if this class does not provide the proper thread safety that you need.
a source to share