wulfgarpro wulfgarpro - 10 months ago 81
C++ Question

Thread join c++ behaviour

If I'm synchronizing threads with

, considering the order of the calls to join, why do I sometimes see the output of


#include <thread>

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

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


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.


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.