我正在编写一个简单的生产者/消费者程序,以更好地理解 C++ 和多线程。 在运行消费者的线程中,我有前两行:
pthread_cond_wait(&storageCond, &storageMutex);
pthread_mutex_lock(&storageMutex);
但是程序卡住了,可能是死锁了。 然后我换了行:
pthread_mutex_lock(&storageMutex);
pthread_cond_wait(&storageCond, &storageMutex);
它奏效了。 有人可以帮我理解为什么这个有效而前者没有吗?
谢谢。
最佳答案
来自 pthread_cond_wait 联机帮助页 (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.
我建议您使用一些很好的包装器库,例如 boost::threads
,或者当您可以访问 C++11 时,您可以使用 std::
线程工具。由于他们使用 RAII 之类的东西,因此它们更容易处理,尤其是在没有线程编程经验的情况下。
关于C++简单的线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7520883/