gpt4 book ai didi

c++ - 在 C++ scott meyers 中检测事件的条件变量用法

转载 作者:太空狗 更新时间:2023-10-29 20:37:42 27 4
gpt4 key购买 nike

我正在阅读 Scott Meyers 所著的 Effective Modern C++ 中的条件变量,下面是文本。

std::condition_variable   cv
std::mutex m

T1 (detecting task)

...
cv.notify_one();


T2 (reacting task)

...
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk);

...
}

这里作者提到如下

Mutexs are used to control access to shared data, but it's entirely possible that the detecting and reacting tasks have no need for such mediation. For example, the detecting task might be responsible for initializing a global data structure, then turning it over to reacting task for use. If the detecting task never access the data structure after initialzing it, and if the reacting task never access it before the detecting task indicates that it's ready, the two tasks will stay out of each other's way through program logic. There will be no need for mutex.

上面的文字我看不懂

  1. 作者所说的“两个任务将通过程序逻辑相互远离”是什么意思?

  2. 作者所说的不需要互斥锁是什么意思?

最佳答案

Mutex 用于解决竞争条件,例如:

A race condition occurs when two or more threads can access shared data and they try to change it at the same time

在您的情况下不会发生,因为在您的结构上完成的操作将在不同的时间范围内完成,即:不会导致任何竞争条件。由于您没有两个线程同时写入,因此您不需要互斥量。

还要考虑到大多数问题出现在您进行“先检查后执行”(例如,“检查”值是否为 X,然后“执行”以执行某项取决于该值为 X 的操作)并且另一个线程执行某项操作时到“检查”和“行为”之间的值。

关于c++ - 在 C++ scott meyers 中检测事件的条件变量用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34065308/

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