如何在超时时停止异步求值函数
How to stop a async evaluating function on timeout?
说我们有一个简单的异步调用,我们想在超时时终止/消除
// future::wait_for
#include <iostream> // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
// call function asynchronously:
std::future<bool> fut = std::async (is_prime,700020007);
// do something while waiting for function to set future:
std::cout << "checking, please wait";
std::chrono::milliseconds span (100);
while (fut.wait_for(span)==std::future_status::timeout)
std::cout << '.';
bool x = fut.get();
std::cout << "n700020007 " << (x?"is":"is not") << " prime.n";
return 0;
}
我们想在第一次超时时就把它杀死。将来找不到方法。
我能找到的最接近停止正在运行的任务的方法是std::packaged_task
reset
方法,但它没有说明它是否可以中断正在运行的工作。那么,如何在不使用boost线程或其他非stl库的情况下杀死异步运行的任务呢?
无法立即停止std::async
。。。但是,您可以这样做,传递一个bool
来终止is_prime
方法,并在超时时抛出异常:
// future::wait_for
#include <iostream> // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
// A non-optimized way of checking for prime numbers:
bool is_prime(int x, std::atomic_bool & run) {
for (int i = 2; i < x && run; ++i)
{
if (x%i == 0) return false;
}
if (!run)
{
throw std::runtime_error("timed out!");
}
return true;
}
int main()
{
// Call function asynchronously:
std::atomic_bool run;
run = true;
std::future<bool> fut = std::async(is_prime, 700020007, std::ref(run));
// Do something while waiting for function to set future:
std::cout << "checking, please wait";
std::chrono::milliseconds span(100);
while (fut.wait_for(span) == std::future_status::timeout)
{
std::cout << '.';
run = false;
}
try
{
bool x = fut.get();
std::cout << "n700020007 " << (x ? "is" : "is not") << " prime.n";
}
catch (const std::runtime_error & ex)
{
// Handle timeout here
}
return 0;
}
为什么能够停止线程是糟糕的
在任意点停止线程是危险的,会导致资源泄漏,其中资源是指针、文件和文件夹的句柄,以及程序应该做的其他事情
杀死线程时,线程可能正在工作,也可能不在工作。无论它在做什么,它都不会完成,任何成功创建的变量都不会调用它们的析构函数,因为没有线程可以运行它们
我在这里概述了一些问题。
我认为不可能从循环本身之外安全地中断正在运行的循环,所以STL不提供这样的功能。当然,可以尝试杀死正在运行的线程,但这并不安全,因为可能会导致资源泄漏。
您可以在is_prime
函数中检查超时,如果发生超时,则从中返回。或者,您可以尝试将对std::atomic<bool>
的引用传递给is_prime
,并在每次迭代中检查其值。然后,当超时发生时,更改main
中原子的值,使is_prime
返回。
相关文章:
- 某些 boost::asio 异步函数是否将处理程序连接到操作,以便处理程序被触发一次?
- 调用boost.asio的异步函数时,线程是什么时候创建的
- 如何处理异步函数中的异常UWP应用程序getFileFrompathAsync(path);
- 如何在 std::future 的向量中调用异步函数
- 如何保持异步函数中使用成员的shared_ptr对象的活动状态?
- 如何声明异步函数
- C++中的异步函数调用
- 异步函数产生不一致的结果
- Windows中的C++异步函数
- Qt 中的异步函数调用
- 如何避免在调用异步函数进行 lambda 回调时出现额外的副本
- 如何创建异步函数
- 异步函数出错
- 如何调用boost::asio异步函数
- 处理c++中的复合异步函数
- std::异步函数串行运行
- 自动删除发送给异步函数的容器/io_service
- 异步函数调用的参数生存期
- c++boost asio异步函数在dll中不起作用
- 无法理解异步函数的值,特别是来自库的值