从C++ 11中的另一个线程解锁一个线程

Yan*_*ick 3 c++ concurrency multithreading mutex c++11

我对C++ 11的thread.h api的了解并不是很广泛(实际上我也不熟悉线程编程,但我最近读了很多,并且知道并发和类似的东西但是我开始使用它,我面临的问题是我还没有遇到过的问题.

我有两个线程函数,比如这些

std::thread(thread1, args); // Spawn thread 1
std::thread(thread2, args); // Spawn thread 2

[...]

int thread1(bunch of args)
{
     lock_thread_2();
     [do stuff]
     while (some condition) {
         [do stuff]
         unlock_thread_2();
     }
}

int thread2(bunch of args)
{
     while (some condition) {
         [do stuff]
         wait_for_thread1_to_unlock_me();
     }
}
Run Code Online (Sandbox Code Playgroud)

我首先考虑使用std :: mutex来做它,但我读到它可能很危险,因为如果我解锁已经解锁的互斥锁并且在它之上它的行为是不确定的,它将无法正常工作,因为mutex.lock()不会不一定会暂停执行(只有当互斥锁已被锁定时才这样做)所以编写它是非常可怕的,我必须将unlock()和lock()调用结合在一起.

这里要注意的重要一点是thread2的执行只受thread1控制,但是thread2永远不会以任何方式锁定thread1.只有thread2被thread1锁定,只有thread1控制执行流程thread2,否则不会.

你会如何以一种干净的方式,支持的方式做到这一点?你愿意举一个代码的例子吗?

谢谢!

Bar*_*rry 5

使用condition_variable:

std::condition_variable cv;

int thread1(bunch of args)
{
     [do stuff]
     while (some condition) {
         [do stuff]
         cv.notify_one();
     }
}

int thread2(bunch of args)
{
     std::mutex mtx;
     std::unique_lock<std::mutex> lk(mtx);

     while (some condition) {
         [do stuff]
         cv.wait(lk);
     }
}
Run Code Online (Sandbox Code Playgroud)

wait()返回时,要么cv已经被notify()-ed ......或者会有一个虚假的唤醒.为了处理后者,添加谓词通常很有帮助.