简体   繁体   English

std :: condition_variable谓词是否在锁定状态下执行?

[英]Is the predicate of std::condition_variable executed under lock?

As condition variable could check whether given predicate is true or not, and return only if it is true (like below snippet), is the predicate running inside the protection of lock included in the condition variable ( mutex m in below snippet)? 由于条件变量可以检查给定谓词是否为真,并且仅在为真时才返回(如代码段下方),因此谓词是否在条件变量中包含的锁保护内运行(代码段下方的mutex m )?

std::condition_variable cv;
std::mutex m;
std::unique_lock<std::mutex> lk;

cv.wait(lk, []{/*predicate*/});

The version of wait() that takes a predicate is equivalent to: 具有谓词的wait()版本等效于:

while (!pred())
    wait(lock);

Hence, the predicate is checked outside the wait(lock) call (and the lock is unlocked only inside that call), meaning that the lock is locked when the predicate is checked. 因此,该谓词是在wait(lock)调用外部进行检查的(并且仅在该调用内部对该锁进行了解锁),这意味着在检查该谓词时,该锁已被锁定。

The call cv.wait(lk, p) is defined by [thread.condition.condvar] to be equivalent to: 调用cv.wait(lk, p)由[thread.condition.condvar]定义为等效于:

while (!p())
    cv.wait(lk);

Moreover, the precondition for wait is that the calling thread holds the lock. 而且, wait的前提是调用线程持有该锁。 Therefore, yes indeed, the predicate check happens under the lock. 因此,是的,确实是在锁下进行谓词检查。

Anything other than this behaviour wouldn't make a lot of sense, since otherwise checking the predicate would produce a data race unless you would provide a separate synchronisation mechanism for the predicate. 除此行为外,没有其他任何意义,因为否则检查谓词将产生数据争用,除非您为谓词提供单独的同步机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM