Ari M
Ari M

Reputation: 1426

C++ simple threading question

I'm writing a simple producer/consumer program to better understand c++ and multithreading. In my thread that ran the consumer i had these first two lines:

    pthread_cond_wait(&storageCond, &storageMutex);
    pthread_mutex_lock(&storageMutex);

But the program got stuck, probably a deadlock. Then i switched the lines:

    pthread_mutex_lock(&storageMutex);
    pthread_cond_wait(&storageCond, &storageMutex);

And it worked. Can someone please help me understand why this worked and the former did not?

Thank You.

Upvotes: 2

Views: 258

Answers (3)

ritesh
ritesh

Reputation: 992

Once a thread resumes from a condition variable wait, it re-aquires the mutex lock. That's why the first sample program got stuck.

The idea is to always do a cond_wait() inside the mutex lock. The cond_wait() will relinquish the lock and atomically start waiting (so that you don't miss a cond_signal() from another thread) and when signaled, cond_wait() will reacquire the mutex to ensure that your critical section has only a single thread running in it.

HTH, this scheme of locking is known as Monitor.

Upvotes: 1

John Humphreys
John Humphreys

Reputation: 39354

This is a little simplified, but you basically need a lock on the mutex you're using in order to do the condition wait - its like a multithreading race condition safeguard. If you need a good description of why, check the UNIX man page with "man pthread_cond_wait" and it gives a nice long speech :)

pthread_cond_wait(&storageCond, &storageMutex); //Wants mutex you don't have locked.
pthread_mutex_lock(&storageMutex);              //Get mutex after its too late.

pthread_mutex_lock(&storageMutex);              //Get mutex first.
pthread_cond_wait(&storageCond, &storageMutex); //Do cond wait with mutex you have.

Upvotes: 1

PlasmaHH
PlasmaHH

Reputation: 16046

From the pthread_cond_wait manpage (http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html):

They are called with mutex locked by the calling thread or undefined behaviour will result.

I suggest that you use some good wrapper library like boost::threads or when you have access to C++11 you use the std:: threading facilities. Since they use things like RAII they are much easier to handle, especially when unexperienced in threads programming.

Upvotes: 5

Related Questions