C ++ 11 wait_for超时

时间:2019-09-19 13:03:39

标签: c++11 timeout futex

我有以下代码

#include <future>
#include <iostream>
#include <string>

int DoTimeCostWork(int nId)
{
//      std::this_thread::sleep_for(std::chrono::milliseconds(10));
        return nId;
}

int main()
{
        for ( int i = 0 ; i < 100000 ; i ++ )
        {
                std::future<int> fut = std::async(std::launch::async,DoTimeCostWork, i);

                std::chrono::steady_clock::duration tSpan(300000);
                if (fut.wait_for(tSpan) == std::future_status::timeout)
                     std::cout << "timeout" << std::endl;
                else
                     std::cout << "ret := " << fut.get() << std::endl;
        }
        return 0;
}

为什么有时会发生超时? 通过strace我看到以下错误消息

11:13:45.333546 clock_gettime(CLOCK_REALTIME, {1568862825, 333557480}) = 0 <0.000009>
11:13:45.333575 futex(0xa88064, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 1, {1568862825, 333857480}, ffffffff) = -1 ETIMEDOUT (Connection timed out) <0.000760>
11:13:45.334370 clock_gettime(CLOCK_REALTIME, {1568862825, 334387226}) = 0 <0.000010>

如何解决超时?

0 个答案:

没有答案