To allow other threads to continue execution, the main thread should
terminate by calling pthread_exit() rather than exit(3). http://man7.org/linux/man-pages/man3...ad_exit.3.html
Based on various documentations and some stackoverflow comments, it seems that pthread_exit terminates main() but does not allow the process to terminate. This way, the other threads are allowed to finish execution without resources becoming invalid or without being abruptly terminated when the process terminates. Here's a schematic representation of parallel programming. For these examples I will be using Hello World as the program in execution. Forward arrows represent x
spawns or executes y and backwards arrows represent a
return from.
The standard single thread case (when you compile a Hello World program and run it):
hello.exe -> main_thread -> main()
This is how your typical program executes, so execution stops in reverse.
hello.exe <- main_thread <- main()
The multithreading case:
hello.exe -> main_thread -> main() ->t1
->t2
Which becomes
hello.exe -> main_thread -> main()
-> t1_thread -> t1()
-> t2_thread -> t2()
If main exits before other threads
hello.exe <- main_thread <- main()
X-> t1_thread -> t1()//X = cancelled
X-> t2_thread -> t2()//X = cancelled
If pthread_exit is called in main
hello.exe <- main_thread <- main()
-> t1_thread -> t1()
-> t2_thread -> t2()
//hello.exe waits until the last thread exits before exiting
How exactly pthread_exit() accomplishes this? I am not sure, but it definitely creates the same effect as if main_thread was another thread. It would be cool if someone who is familiar with the inner workings of pthread could clarify if main_thread is being blobked until the last child thread stops execution or if it is able to change the execution of hello at the core? I mean, if the latter is possible, how could you change the meaning of main_thread from main to !main? Anyways, the reason you weren't getting any output is because the other threads were cancelled before they could start/continue executing! I hope this explanation helps!