C++简单的线程问题

标签 c++ multithreading pthreads producer-consumer

我正在编写一个简单的生产者/消费者程序,以更好地理解 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/

相关文章:

c - 在 POSIX 中将整数值转换为 void* 并再次返回是否总是安全的?

c++ - 传递一个函数和一个整数的函数。警告 : passing argument of "" from incompatible pointer type

c++ - 启动浏览器的 Posixy 方式?

c++ - 为 PCL c++ 代码创建的 boost.python 模块导入错误

c++ - 如何使用 for 循环多次提示用户输入不同的文件名?

android - 在 ListView 项目按钮单击时需要有关 AsyncTask 的帮助

c++ - 结构中的 vector 不会让我 push_back

python - multiprocessing.Pool.imap_unordered 的内存使用量稳步增长

java - 双重检查锁定作为反模式

java - 精准消费时间解决方案