How to complete std :: future?

I am confused about something about C ++ 11 std::future . I want to dynamically balance the workload, so if there are several processors in standby mode, I create std::future with std::async to separate the remaining data. It works great.

 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, when some special data elements were found, all other data will be discarded, and the program should immediately give the final result, 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 f created out of my control, do they still work after returning? how can i finish them to free up the processor time they used?

+6
source share
1 answer

The C ++ standard does not make it possible to cancel the future or stop the flow. There is a reason for this.

It is not possible to find out if it is safe to stop a thread at a specific point in time. A thread can receive resources that must be completed. Only the running stream itself knows when to stop safely.

Even if the underlying low-level API provides a call to kill any thread of its own, it is certainly not a good way to go due to the above circumstances.

The traditional solution to this problem is signaling the stream and canceling it from the inside. A trivial implementation can be based on a single atomic bool value.

+8
source

All Articles