Parallel calculation, where only the fastest solution wins C ++

I am writing a program that creates several threads (5-20) at a time in order to calculate iterations of one problem in parallel. Now, any of these threads can find the right solution, after which this solution (in the form of an object reference) should be returned to the main thread to stop all other threads and create new ones based on this solution.

When a solution is found, it is very important that the main thread respond quickly to stopping / pausing threads and processing the solution.

I looked at the observer pattern, C ++ 11 methods, std::asyncand std::future/ objects promise, but usually examples expect results from all threads, which are then collected and processed. In my application, only one “winner” thread can provide a solution, but I cannot know in advance what it will be.

Since I'm new to concurrent programming, I wonder what is the best way to implement this? What is the most efficient way to make the main thread wait for the result of only one of several other threads / concurrent tasks?

Edit to clarify: I have a real-time signal that needs to be analyzed. I have different algorithms that can determine a subset of different system states. The “win” algorithm corresponds to the signal of one of these categories, so that the current state of the system is known. Depending on the current state, the system may go into different states in the future, which must be detected again. Currently, all these algorithms are executed sequentially in a cycle until they find a suitable category, and at this moment the main thread sets the parameters for the subsequent detection interval. But with the parallel computation of these different algorithms, I could significantly increase the efficiency.

+4
source share
1 answer

: , , . , , , .

, -. - : , , . : , , . . , concurrency , , .

- condition_variable. , . , , , , , , condition_variable. . , , concurrency, , , , .

atomic, . , . , ​​ , , . , , . , . , .

+4

Source: https://habr.com/ru/post/1695805/