gpt4 book ai didi

c++ - boost 线程和 try_join_for 每次都给出不同的输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:37 25 4
gpt4 key购买 nike

假设我有以下代码:

#include <boost/chrono.hpp>
#include <boost/thread.hpp>

#include <iostream>

int main()
{
boost::thread thd([]{ std::cout << "str \n"; });

boost::this_thread::sleep_for(boost::chrono::seconds(3));

if (thd.try_join_for(boost::chrono::nanoseconds(1)))
{
std::cout << "Finished \n";
}
else
{
std::cout << "Running \n";
}
}

每次启动该程序时,MSVC-12.0 和 boost 1.55 都会给我不同的输出。例如,

str
Finished

str
Finished

str
Running

当我将 boost::chrono::nanoseconds 更改为 boost::chrono::microseconds 时,输出看起来符合预期。

为什么?我究竟做错了什么?这是boost库中的错误吗?是否有关于 boost 错误跟踪器的票证?

提前致谢。

最佳答案

您的程序只是在竞争,很可能是因为 1 纳秒太短了。

try_join_for 是通过调用 try_join_until 实现的,该函数将尝试加入直到达到某个时间点:

// I stripped some unrelated template stuff from the code
// to make it more readable

bool try_join_for(const chrono::duration& rel_time)
{
return try_join_until(chrono::steady_clock::now() + rel_time);
}

bool try_join_until(const chrono::time_point& t)
{
system_clock::time_point s_now = system_clock::now();
bool joined= false;
do {
Clock::duration d = ceil<nanoseconds>(t-Clock::now());
if (d <= Clock::duration::zero())
return false; // in case the Clock::time_point t is already reached
// only here we attempt to join for the first time:
joined = try_join_until(s_now + d);
} while (! joined);
return true;
}

现在的问题是 try_join_until 将在尝试加入之前检查是否已达到请求的 time_point。如您所见,它需要执行另外两次对 clock::now() 的调用和一些计算,以将获得的值与用户指定的截止日期进行比较。这可能会或可能不会在时钟跳到您给定的 1 纳秒截止日期之前完成,从而导致输出的不可预测性。

请注意,通常像这样的时序相关代码是脆弱的。即使有毫秒级的超时,如果你在执行过程中的一个坏点被抢占并且 CPU 负载很高,在极少数情况下你可能会错过最后期限。因此,请务必谨慎选择截止日期,切勿假设截止日期在所有可能的情况下都足够大。

关于c++ - boost 线程和 try_join_for 每次都给出不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22991484/

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