gpt4 book ai didi

c++ - 为什么 lock_guard 可以通过 unique_lock 得到一个已经锁定的互斥体?

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:56 24 4
gpt4 key购买 nike

我正在阅读使用 condition_variable 的示例代码 here .我在下面发布代码:

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
// Wait until main() sends data
std::cout << "------------------------\n";
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return ready;});

// after the wait, we own the lock.
std::cout << "Worker thread is processing data\n";
data += " after processing";

// Send data back to main()
processed = true;
std::cout << "Worker thread signals data processing completed\n";

// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv.notify_one();
}

int main()
{
std::thread worker(worker_thread);

data = "Example data";
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();

// wait for the worker
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return processed;});
}
std::cout << "Back in main(), data = " << data << '\n';

worker.join();

return 0;
}

我的问题是 worker_thread 首先启动,所以我假设互斥量 mworker_thread 锁定,但为什么在main 互斥体 m 仍然可以被 lock_guard 锁定吗?

最佳答案

条件变量只是三脚架的一部分。

三部分分别是条件变量、状态和守护状态的互斥体。

条件变量提供了一种在状态改变时进行通知的机制。

此操作使用所有 3 个:

cv.wait(lk, []{return ready;})

条件变量的方法需要一个锁(必须已获取)和一个 lambda(用于测试状态)。

wait 方法中,lk解锁,直到条件变量检测到一条消息(可能是虚假的)。当它检测到一条消息时,它会重新锁定互斥锁并运行测试(其目标是确定检测是否虚假的)。如果测试失败,它会解锁并再次等待:如果测试通过,它会保持锁定状态并退出。

还有“测试抛出”路径,这会导致不同的锁定状态,具体取决于您的代码实现的标准版本(C++11 有缺陷,IIRC)。

您错过的重要事情是 wait 解锁传入的互斥量。

关于c++ - 为什么 lock_guard 可以通过 unique_lock 得到一个已经锁定的互斥体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32030862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com