C++简单的线程问题

Sna*_*gon 2 c++ multithreading pthreads producer-consumer

我正在编写一个简单的生产者/消费者程序来更好地理解c ++和多线程.在我运行消费者的线程中,我有前两行:

    pthread_cond_wait(&storageCond, &storageMutex);
    pthread_mutex_lock(&storageMutex);
Run Code Online (Sandbox Code Playgroud)

但程序陷入困境,可能是一个僵局.然后我换了线:

    pthread_mutex_lock(&storageMutex);
    pthread_cond_wait(&storageCond, &storageMutex);
Run Code Online (Sandbox Code Playgroud)

它奏效了.有人可以请帮助我理解为什么这有效,而前者没有?

谢谢.

Pla*_*aHH 5

从pthread_cond_wait联机帮助页(http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html):

它们是由调用线程锁定的互斥锁调用的,否则将导致未定义的行为.

我建议您使用一些好的包装器库,boost::threads或者当您可以访问C++ 11时使用std::线程工具.由于它们使用像RAII这样的东西,因此它们更易于处理,尤其是在没有经验的线程编程时.