简体   繁体   English

如何终止std :: future?

[英]How to terminate a std::future?

I'm confused by something about C++11 std::future . 关于C ++ 11 std::future事情让我感到困惑。 I want to balance work load dynamically, so if there are some processors idle, I create a std::future with std::async to divide the remaining data. 我想动态平衡工作负载,所以如果有一些处理器空闲,我用std::async创建一个std::future来划分剩余的数据。 It works fine. 它工作正常。

std::future<int> f[MAX_CHILD];
for ( each data item ){
    if ( found_idle_processor )
        f[i] = std::async( ... );

    process();
}

// At last, query the result of f.
for ( each future )
    hold = f[i].get();

But sometimes, once some special data items were found, all other data will be discarded and the program should give the final result immediately, then another task will be launched. 但有时,一旦找到一些特殊数据项,所有其他数据将被丢弃,程序应立即给出最终结果,然后将启动另一个任务。

std::future<int> f[MAX_CHILD];
for ( each data item ){
    if ( found_idle_processor )
        f[i] = std::async( ... );

    process();

    if ( found_special_item )
        return final_result;
}
// At last, query the result of each f.
for ( each future )
    hold = f[i].get();

But the created f are out of my control, are they still running after return? 但是创建的f不受我的控制,它们在返回后仍在运行吗? how can I terminate them to release CPU time they used? 如何终止它们以释放它们使用的CPU时间?

The C++ standard does not provide a way to cancel a future or stop a thread. C ++标准没有提供取消未来或停止线程的方法。 There is a reason for that. 这是有原因的。

There is no way to know if a thread can be stopped safely at some particular moment in time. 无法知道线程是否可以在某个特定时刻安全停止。 The thread may have acquired resources which should be finalized. 线程可能已经获得了应该最终确定的资源。 Only the running thread itself knows when it is safe to stop. 只有正在运行的线程才知道何时可以安全停止。

Even if the underlying low-level API provides a call to kill any thread at will, this is definitely not a good way to go because of the above-mentioned circumstances. 即使底层的低级API提供了随意杀死任何线程的调用,由于上述情况,这绝对不是一个好的方法。

Traditional solution to this issue is signalling the thread and cancelling it from within. 这个问题的传统解决方案是发出信号并从内部取消它。 A trivial implementation may be based on a single atomic bool flag. 一个简单的实现可能基于单个原子bool标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM