'std::condition_variable::wait_for"经常调用谓词

`std::condition_variable::wait_for` calls the predicate very often

本文关键字:常调用 调用 谓词 wait std condition variable for quot      更新时间:2023-10-16

请考虑以下代码片段:

#include <iostream>
#include <condition_variable>
#include <chrono>
#include <mutex>
int main () {
std::mutex y;
std::condition_variable x;
std::unique_lock<std::mutex>lock{y};
int i = 0;
auto increment = [&] {++i; return false;};
using namespace std::chrono_literals;
//lock 5s if increment returns false
//let's see how often was increment called?
x.wait_for(lock, 5s, increment);
std::cout << i << std::endl;
//compare this with a simple loop:
//how often can my system call increment in 5s?
auto const end = std::chrono::system_clock::now() + 5s;
i = 0;
while (std::chrono::system_clock::now() < end) {
increment();
}
std::cout << i;
}

据我wait_for了解,i应该是 O(1( 在wait_for之后(让我们假设虚假解锁很少见(。

但是,我i ~= 3e8
kernel 4.17.14, Intel(R) Core(TM) i7-6700 CPU @ 3.40GHzi ~= 8e6
kernel 3.10.0, Intel(R) Xeon(R) CPU E5-2630 v4 @ 2.20GHz

这听起来很有趣,所以我通过与运行 5 秒的简单循环进行比较来检查。i的结果大致相同,只有5-10%的差异。

问:
wait_for在做什么?它是否按预期工作,我只是理解错误地理解了 cpp首选项,还是我搞砸了?

第二,(可选(问题:i的巨大差异从何而来?

附加信息: (gcc7.3gcc8.2clang6.0(, 标志:-O3 --std=c++17都产生可比较的结果。

libstdc++有一个不幸的编译能力,似乎在没有pthread的情况下工作,但它将无法正常工作。

请参阅此libstdc++错误:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58929

您需要将"-pthread"添加到编译命令中。

编译时需要-pthread标志添加到 gcc,例如在 RE 上的 gcc 5.1.0 上:

without pthread: 49752692
with pthread: 2

你需要使用 g++ 的-pthread标志链接到 pthread 库:

g++ cond_test.cpp -pthread

大多数 Linux 系统要求您链接到pthread库才能使用线程功能。然而,使用标准C++线程的程序似乎在没有显式链接到pthread的情况下成功链接,而是在运行时产生未定义的行为(它经常崩溃,但使用此代码似乎不会,而是产生意外的行为(。

此代码的示例:

$ g++ t.cpp  && ./a.out
5817437
18860410
$ g++ t.cpp  -pthread && ./a.out
2
19718764