C++ 如果超时已过,如何中止async()

C++ 如果超时已过,如何中止async(),c++,multithreading,c++11,asynchronous,c++-standard-library,C++,Multithreading,C++11,Asynchronous,C++ Standard Library,我对async()函数或任何其他解决问题的方法有疑问。我向服务器发送指定类型的消息,并等待特定的消息 答复。 我有一个函数receive(),它等待服务器的响应。我在async()中调用此函数 代码示例: while (true) { future_receive = std::async(std::launch::async, [&] { receive(); }); do { status = future_receive.w

我对async()函数或任何其他解决问题的方法有疑问。我向服务器发送指定类型的消息,并等待特定的消息 答复。 我有一个函数receive(),它等待服务器的响应。我在async()中调用此函数

代码示例:

while (true) {
    future_receive = std::async(std::launch::async, [&] {
        receive();
    });

    do {
        status = future_receive.wait_for(chrono::seconds(timeLimit));
        if (status == std::future_status::timeout){
            //if timeout, abort async() function
        }
    } while (status != std::future_status::ready);
}
我有什么问题?在这种情况下,如果我得到“timeout”,async()函数将在, 会等到某件事发生,即使它永远不会发生,在下一个循环中会再次被调用, 新的线程将被创建。如何避免这种情况


如何在“超时”已过时中止async()。也许没有async()的其他方法可以解决这个问题。我只想使用C++的标准库?< /p> < p>异步线程必须合作检查它是否继续工作或放弃,没有没有它的合作就没有办法强制它停止。 一种方法是将
receive()
调用替换为具有超时的类似调用,并让线程在超时后放弃,或者在超时后检查标志以指示是否继续

while (true) {
    std::atomic<bool> stop{false};
    future_receive = std::async(std::launch::async, [&] {
        while (!stop)
          try_receive(std::chrono::seconds(1));
    });

    do {
        status = future_receive.wait_for(chrono::seconds(timeLimit));
        if (status == std::future_status::timeout){
            stop = true;
        }
    } while (status != std::future_status::ready);
}
这假设在
receive()
调用中的某个地方有一个Pthreads取消点,因此
pthread\u cancel
将中断它

(这比我想要的稍微复杂一些。最初需要在原子中存储一些已知的值,以便处理异步线程在调用线程获得超时并试图取消它时还没有开始运行的情况。要处理这个问题,我存储调用线程的ID,然后等待它被更改b。)在调用
pthread\u cancel
之前

while (true) {
    std::atomic<pthread_t> tid{ pthread_self() };
    future_receive = std::async(std::launch::async, [&] {
        tid = pthread_self();
        receive();
    });

    do {
        status = future_receive.wait_for(chrono::seconds(timeLimit));
        if (status == std::future_status::timeout){
            while (tid == pthread_self())
            { /* wait for async thread to update tid */ }
            pthread_cancel(tid);
        }
    } while (status != std::future_status::ready);
}