C++;简单线程问题 我编写了一个简单的生产者/消费者程序,以更好地理解C++和多线程。 在运行消费者的线程中,我有以下两行代码: pthread_cond_wait(&storageCond, &storageMutex); pthread_mutex_lock(&storageMutex);
但是程序被卡住了,可能是死锁。 然后我换了台词:C++;简单线程问题 我编写了一个简单的生产者/消费者程序,以更好地理解C++和多线程。 在运行消费者的线程中,我有以下两行代码: pthread_cond_wait(&storageCond, &storageMutex); pthread_mutex_lock(&storageMutex);,c++,multithreading,pthreads,producer-consumer,C++,Multithreading,Pthreads,Producer Consumer,但是程序被卡住了,可能是死锁。 然后我换了台词: pthread_mutex_lock(&storageMutex); pthread_cond_wait(&storageCond, &storageMutex); 它成功了。 有人能帮我理解为什么这样做有效而前者没有 谢谢。从pthread\u cond\u wait手册页(): 它们被调用线程锁定或未定义的互斥锁调用 结果会是你的行为 我建议您使用一些好的包装器库,比如boost::threads,或
pthread_mutex_lock(&storageMutex);
pthread_cond_wait(&storageCond, &storageMutex);
它成功了。
有人能帮我理解为什么这样做有效而前者没有
谢谢。从pthread\u cond\u wait手册页(): 它们被调用线程锁定或未定义的互斥锁调用 结果会是你的行为
我建议您使用一些好的包装器库,比如
boost::threads
,或者当您可以访问C++11时,您可以使用std::
线程工具。因为它们使用RAII之类的东西,所以更容易处理,特别是在没有线程编程经验的情况下。这有点简化,但基本上需要对所使用的互斥锁进行锁定,以便执行条件等待-就像多线程竞争条件保护一样。如果您需要很好地描述原因,请查看UNIX手册页上的“man pthread\u cond\u wait”,它会给出一段很长的演讲:)
一旦线程从条件变量wait恢复,它将重新获得互斥锁。这就是为什么第一个示例程序被卡住了 其思想是始终在互斥锁内执行cond_wait()。cond_wait()将放弃锁并自动开始等待(这样您就不会错过来自另一个线程的cond_信号()),当发出信号时,cond_wait()将重新获取互斥锁,以确保关键部分中只有一个线程在运行 HTH,这种锁定方案称为
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.