c++如何实现可停止的未来函数调用
C++ how to implment a stoppable future function call?
我想在超时时间后执行一个函数,如:
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
}
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- c++如何实现可停止的未来函数调用