如何终止std :: future? [英] How to terminate a std::future?

查看:125
本文介绍了如何终止std :: future?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++ 11 std :: future 感到困惑。我想动态地平衡工作负载,所以如果有一些处理器空闲,我用 std :: async std :: future c $ c>划分剩余数据。

I'm confused by something about 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. 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();

但是创建的 f 不属于我控制,返回后它们仍在运行吗?我该如何终止它们以释放它们使用的CPU时间?

But the created f are out of my control, are they still running after return? how can I terminate them to release CPU time they used?

推荐答案

C ++标准没有提供取消未来或停止线程。

The C++ standard does not provide a way to cancel a future or stop a thread. 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.

即使底层的低级API提供了一个可以随意杀死任何线程的调用,这绝对不是

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.

此问题的传统解决方案是发信号通知线程并从内部取消该线程。一个简单的实现可能基于单个原子 bool 标志。

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.

这篇关于如何终止std :: future?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆