std::mutex 不能在 std::thread 之间共享

std::mutex can't be shared among std::thread

本文关键字:std 之间 共享 thread 不能 mutex      更新时间:2023-10-16

在下面的代码中,我想mLooperMutex不能被子线程获取。但程序输出相当令人惊讶。看起来在std::thread中捕获的mLooperMutex与主线程中的mLooperMutex不同。

但是如果我将 std::thread 的 detach(( 调用更改为 join((,这将导致死锁,因为 mLooperMutex 已被主线程锁定。

如果我想在不同的线程中使用mLooperMutex,这个程序有什么问题吗?

A.输出: 主:等待电汇开始
子项:获取锁开始
子项:获取锁完成
孩子:通知一个开始
孩子:通知一个完成
主:等待电汇完成

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
int main()
{
    std::condition_variable looperSet;
    bool child_done = false;
    std::mutex mLooperMutex;
    cout << "main: acquiring lock begin" << endl;
    std::unique_lock<std::mutex> lock(mLooperMutex);
    cout << "main: acquiring lock done" << endl;
    std::thread{[&mutex=mLooperMutex, &looperSet, &child_done] () {
        cout << "child: acquiring lock begin" << endl;
        std::unique_lock<std::mutex> lock(mutex);
        cout << "child: acquiring lock done" << endl;
        child_done = true;
        lock.unlock();
        cout << "child: notify one begin" << endl;
        looperSet.notify_one();
        cout << "child: notify one done" << endl;

    }}.detach();
    cout << "main: wait cond begin" << endl;
    looperSet.wait(lock, [&child_done]{ return child_done; });
    cout << "main: wait cond done" << endl;
    return 0;
}
之所以

可以在子线程中获取mLooperMutex,是因为锁由 looperSet.wait 释放:

// This unlocks "lock", and then locks it again afterwards.
looperSet.wait(lock, [&child_done]{ return child_done; });

这不适用于.join()的原因是.join()等待线程完成才能继续,线程在释放锁之前无法完成,而释放锁looperSet.wait().join()完成之前不会运行。

创建一个线程然后立即调用.join()不是很有用,你最好直接运行代码而不是使用线程。