开发者

C++ simple threading question

开发者 https://www.devze.com 2023-04-06 16:04 出处:网络
I\'m writing a simple producer/cons开发者_JAVA百科umer program to better understand c++ and multithreading.

I'm writing a simple producer/cons开发者_JAVA百科umer 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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号