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();
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?
It's simple: You can't. In fact, there is no way of canceling either futures or threads in the standard.
The C++11 does not have direct method to terminate the threads. The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object.
std::future A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads. "Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions: async. promise::get_future.
The function template async runs the function f asynchronously (potentially in a separate thread which might be a part of a thread pool) and returns a std::future that will eventually hold the result of that function call. 1) Behaves as if (2) is called with policy being std::launch::async | std::launch::deferred.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With