I am writing a C++ code to do a task on different threads and await the result to return to the main function.
Each thread can take different timing and might result in a correct or incorrect result.
I start the threads as follows:
std::thread p1(&process1, (void*)&p1Data);
std::thread p2(&process2, (void*)&p2Data);
std::thread p3(&process3, (void*)&p3Data);
.
.
.
(Multiple threads are created this way).
The Process Functions can be summarized like this:
\\ThreadData is a structure that contains all the data for the thread
void process1(void *data)
{
ThreadData * tData = (ThreadData*) data;
ResultObject * result = data->result;
.
.
.
\\Process to calculate Result using data
}
in main after I launch those threads I join them to await final results and then check the correct one.
p1.join();
p2.join();
.
.
.
p1result = p1Data.result;
p2result = p2Data.result;
.
.
.
.
.
.
if (p1result)
{
return p1Data;
}
if (p2result)
{
return p2Data;
}
But the issue is (for sake of simplicity I will consider that p1 is the fastest thread) if p1 is done with correct result, I am still forced to wait the join for all the other threads to get my final result while p1 that was done first can contain the correct one and I can just terminate on it.
How can I check on each thread when it is done if the result is ok so that I can terminate the remaining threads without the need on waiting on them to be done (ie if p2 finished before p1 and the result of p2 is acceptable, i can return p2Data and just terminate all the remaining threads without)