How to terminate a std::future?

后端 未结 1 696
谎友^
谎友^ 2021-01-17 13:43

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<

相关标签:
1条回答
  • 2021-01-17 14:26

    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.

    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.

    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.

    0 讨论(0)
提交回复
热议问题