2011-09-22 123 views
2

我正在写一个简单的生产者/消费者程序,以更好地理解C++和多线程。 在我的线程运行过的消费者,我有这些前两行:C++简单线程问题

pthread_cond_wait(&storageCond, &storageMutex); 
    pthread_mutex_lock(&storageMutex); 

但程序卡住了,可能是一个僵局。 然后我换行:

pthread_mutex_lock(&storageMutex); 
    pthread_cond_wait(&storageCond, &storageMutex); 

和它的工作。 有人可以帮我理解为什么这个工作,前者没有?

谢谢。

回答

5

从调用pthread_cond_wait手册页(http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html):

他们被称为与互斥调用线程或未定义 行为将导致锁定。

我建议你使用一些好的包装库像boost::threads,或当你有机会获得C++ 11使用std::线程设施。由于他们使用像RAII这样的东西,他们更容易处理,特别是在线程编程方面没有经验的时候。

1

这是一个简单的,但你基本上需要对你正在使用的互斥锁进行锁定,以等待状态 - 它像多线程竞争条件保护。如果你需要的为什么,用“man调用pthread_cond_wait”检查UNIX man页面一个很好的说明和一旦线程从条件变量等待恢复它给出了一个很好的长篇大论:)

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. 
1

,它重新aquires的互斥锁。这就是为什么第一个示例程序卡住了。

这个想法是总是在里面做一个cond_wait()这个互斥锁。 cond_wait()会放弃锁并自动开始等待(这样就不会错过来自另一个线程的cond_signal()),并且在发信号时,cond_wait()将重新获取该互斥锁以确保关键部分只有一个线程在其中运行。

HTH,这种锁定方案被称为Monitor