Affect C ++ Behavior

If I synchronize the threads with join() , given 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 understand the behavior if I had some interleaving at the beginning before the connection calls, followed by all the remaining t1 outputs, followed by the remaining t2 outputs. But instead, I see all t2, then all t1, or vice versa.

+7
c ++ multithreading
source share
4 answers

join affects the current thread that you are calling join , not the associated thread.

basically, join makes the current thread wait for another thread to complete execution. it does not affect the start of another thread or in what order compared to other threads.

in your example, there is no guarantee which of the t1 and t2 threads will be started and finished first. the only guarantee is that the main thread waits for t1 first, then for t2 , then writes the message to standard output.

+8
source share

The order of the calls does not mean that your output will be ordered the same way, and since you execute threads at the same time, you cannot control which implementation is first executed on the CPU.

If you need to get t1 to do something before t2 just use Semaphores .

+1
source share

join does not affect the thread to which it is applicable. It simply blocks the thread that called it until the thread to which it applied has completed and then continues to execute. Thus, the order of the join calls does nothing in the order in which the threads execute.

By the way, in

 std::thread t1(callFromthread, 1); if (t1.joinable()) t1.join(); 

the test is redundant. If you do not call detach , the std::thread objects join.

+1
source share

The order in which you join does not determine or affect the order in which threads are executed. Thus, the output from both streams can be in any order (or alternating).

+1
source share

All Articles