Reputation: 2496
I have problem with this simple wrapper of mutex / cond wait class. I use it to protect queue of connected clients and to notify threads in the wait state that there are new clients connected, but application crashed with Segmentation Failed at
client_socket_fd = clients_for_threads_q.front();
when its is under stress test only (many clients connected )
Wait at the thread:
MUTEXCONDSIGNAL_for_workers.lock();
if ( clients_for_threads_q.empty() )
{
MUTEXCONDSIGNAL_for_workers.wait_signal();
}
client_socket_fd = clients_for_threads_q.front(); // CRASHED !!!!
clients_for_threads_q.pop();
MUTEXCONDSIGNAL_for_workers.unlock();
of course clients_for_threads_q ptotected on writing
MUTEXCONDSIGNAL_for_workers.lock();
clients_for_threads_q.push (client_socket_fd);
MUTEXCONDSIGNAL_for_workers.send_signal();
MUTEXCONDSIGNAL_for_workers.unlock();
Upvotes: 2
Views: 177
Reputation: 206841
pthread_cond_wait
can have spurious wake ups.
When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_wait() or pthread_cond_timedwait() functions may occur. Since the return from pthread_cond_wait() or pthread_cond_timedwait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.
You need to change your waiter if
condition to a loop:
while ( clients_for_threads_q.empty() )
{
MUTEXCONDSIGNAL_for_workers.wait_signal();
}
Upvotes: 4