0

I have parallely launched 5 threads which are calling specific function. If one of them returns some specific value, I need to terminate the further processing of all other remaining threads and the specific function is called asynchronously in the onMessage() method.

Rushabh
  • 73
  • 1
  • 8

1 Answers1

1

Pass a std::atomic<bool>& terminate_flag to all launched threads. When one process find the searched for value, update the terminate_flag. All threads should be running an infinite loop? Modify the loop to exit when the terminate_flag gets set to true.

void thread_function(std::atomic<bool>& terminate_flag, T& search_value, ...)
{
    while(terminate_flag == false)
    {
        ...do stuff...
        if (found_value == search_value)
        {
            terminate_flag = true;
        }
    }
}
JohnFilleau
  • 4,045
  • 1
  • 15
  • 22
  • but even using this, thread_function will run atleast once in each thread right? @John – Rushabh Feb 27 '20 at 08:49
  • If one thread happens to find the value before a second thread gets to even start, then that second thread won't run. Well, it will *run*, but `terminate_flag` will be set to `true` and it will skip everything in the loop and then terminate. – JohnFilleau Feb 27 '20 at 14:10