wulfgarpro wulfgarpro - 3 months ago 31
C++ Question

Thread join c++ behaviour

If I'm synchronizing threads with

join()
, considering the order of the calls to join, why do I sometimes see the output of
t1
after
t2
?

i.e.

#include <thread>

void callFromThread(int id) {
int i = 1000;
while(i != 0) {
printf("%s %d\n", "hi from thread", id);
i--;
}
}

int main(void) {
std::thread t1 (callFromThread, 1);
std::thread t2 (callFromThread, 2);

t1.join();
t2.join();

printf("%s\n", "bye from main!");
return 0;
}


I could make sense of the behaviour if I had some interleaving in the beginning before the join calls, followed by all remaining t1 outputs, followed by the remaining t2 outputs. But, instead I'm seeing all t2 then all t1, or vice-versa.

Answer

join affects the current thread you call join, not the thread which is joined.

basically, join makes the current thread wait for another thread to finish executation. it has no affect on when the other thread is scheduled to run, or on what order compared to other threads.

in your example, there is no guarantee which of the thread t1 and t2 will run and finish first. the only guarantee is that the main thread waits for t1 first, then for t2, then logs a message to stdout.