c++如何实现可停止的未来函数调用

C++ how to implment a stoppable future function call?

本文关键字:未来 函数调用 何实现 实现 c++      更新时间:2023-10-16

我想在超时时间后执行一个函数,如:

sleep(1000); 
doWork();

但是在超时到达之前,我可以在这个线程或其他线程中停止执行,例如:

if(someCondition)
{
    stop the doWork() it is not started.
}

是否有任何现有的std/boost类来完成这种任务?

您可以使用一个变量的组合来指示工作是否需要与一个定时条件变量相结合:您将等待睡眠时间,如果等待结束,您将检查工作是否应该中止,是否需要更多的睡眠(条件变量总是可以虚假地停止等待),或者工作可以开始:

bool                    do_work(true);
std::mutex              mutex;
std::condition_variable condition;
std::chrono::time_point<std::chrono::steady_clock> abs_time(
     std::chrono::steady_clock::now() + std::chrono::milliseconds(1000));
std::unique_lock<std::mutex> kerberos;
if (condition.wait_until(kerberos, abs_time, [&]{ return do_work; })) {
    // do the work
}

取消工作的另一个线程将获得互斥锁,将do_work设置为false,将notify_one()设置为条件变量。

一个互斥锁将完成——线程1等待互斥锁,或者超时。如果第二个线程重置互斥锁,那么第一个线程将在超时前停止阻塞。

在Windows上,你通常使用Event来做这件事,但是boost有条件变量似乎做同样的事情——将一个可等待的事件传递给另一个线程。

这是一个简洁的问题,但我认为最好的解决方案取决于您的应用程序的需求和约束。例如,您是否可以使用一个繁忙等待睡眠函数来轮询条件,或者您是否需要一些不使用那么多CPU的功能?

这是一个可能适合你的解决方案的第一个尝试:

#define SLEEP_RESOLUTION 1000 // A value in microseconds
void do_work_with_delay(int delay_time) { // Specify the delay in ms
    bool condition_reached = sleep_and_check(delay_time);
    if (condition_reached) {
        return;
    }
    do_work();
}

bool sleep_and_check(int delay_time) {
    int accumulated_delay = 0;
    while (accumulated_delay < delay_time*1000) { // Loop until we have waited 
                                             // the whole delay_time
        if (someCondition) // Check the condition, return true if it has been met
            return true;
        usleep(SLEEP_RESOLUTION); // Condition not met, sleep and check again next time
        accumulated_delay += SLEEP_RESOLUTION;
    }
    return false; // Return false to show the whole time 
                  // went by without meeting the condition
}