C++简单的线程问题
我正在编写一个简单的生产者/消费者程序,以更好地理解 C++ 和多线程。 在运行消费者的线程中,我有前两行:
pthread_cond_wait(&storageCond, &storageMutex);
pthread_mutex_lock(&storageMutex);
但是程序卡住了,可能是死锁。 然后我换了台词:
pthread_mutex_lock(&storageMutex);
pthread_cond_wait(&storageCond, &storageMutex);
结果成功了。 有人可以帮我理解为什么这个有效而前者无效吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自 pthread_cond_wait 手册页(http://pubs.opengroup.org /onlinepubs/7908799/xsh/pthread_cond_wait.html):
我建议您使用一些好的包装库,例如
boost::threads
,或者当您可以访问 C++11 时,您可以使用std::
线程工具。由于他们使用 RAII 之类的东西,因此更容易处理,特别是在没有线程编程经验的情况下。From the pthread_cond_wait manpage (http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html):
I suggest that you use some good wrapper library like
boost::threads
or when you have access to C++11 you use thestd::
threading facilities. Since they use things like RAII they are much easier to handle, especially when unexperienced in threads programming.这有点简化,但是您基本上需要锁定正在使用的互斥锁才能执行条件等待 - 它就像多线程竞争条件保护措施。如果您需要详细说明原因,请查看 UNIX 手册页中的“man pthread_cond_wait”,它给出了一个很好的长篇演讲:)
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 :)
一旦线程从条件变量等待中恢复,它就会重新获取互斥锁。这就是第一个示例程序卡住的原因。
这个想法是始终在互斥锁内执行 cond_wait()。 cond_wait() 将放弃锁并自动开始等待(这样您就不会错过来自另一个线程的 cond_signal()),并且当收到信号时, cond_wait() 将重新获取互斥体以确保您的临界区只有一个线程运行在其中。
HTH,这种锁定方案称为监视器。
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.