<分区>
Possible Duplicate:
Is there a way to cancel/detach a future in C++11?
有一个使用 std::future
和 std::async
异步运行的成员函数。在某些情况下,我需要取消它。 (该函数连续加载附近的对象,有时对象在加载时会超出范围。)我已经阅读了 this question 的答案。解决了同样的问题,但我无法让它工作。
这是与我的实际程序具有相同结构的简化代码。在异步运行时调用 Start()
和 Kill()
会因 input
的访问冲突而导致崩溃。
在我看来,代码应该按如下方式工作。当调用 Kill()
时,运行标志被禁用。下一个命令 get()
应该等待线程结束,它很快就会这样做,因为它会检查运行标志。线程取消后,input
指针被删除。
#include <vector>
#include <future>
using namespace std;
class Class
{
future<void> task;
bool running;
int *input;
vector<int> output;
void Function()
{
for(int i = 0; i < *input; ++i)
{
if(!running) return;
output.push_back(i);
}
}
void Start()
{
input = new int(42534);
running = true;
task = async(launch::async, &Class::Function, this);
}
void Kill()
{
running = false;
task.get();
delete input;
}
};
线程似乎没有注意到将运行标志切换为 false。我的错误是什么?