I\'m studying threads in C and I have this theoretical question in mind that is
ID: 652866 • Letter: I
Question
I'm studying threads in C and I have this theoretical question in mind that is driving me crazy. Assume the following code:
1) void main() {
2) createThread(...); // create a new thread that does "something"
3) }
After line 2 is executed, two paths of execution are created. However I believe that immediately after line 2 is executed then it doesn't even matter what the new thread does, which was created at line 2, because the original thread that executed line 2 will end the entire program at its next instruction. Am I wrong? is there any chance the original thread gets suspended somehow and the new thread get its chance to do something (assume the code as is, no sync between threads or join operations are performed)
Explanation / Answer
While the details will depend on the actual thread model of your thread library (eg. pthreads, the POSIX thread library), some general observations hold.
Without explicit or implied syncing you have no guarantees about the serialization of threaded code. The platform running your code might execute some of the thread's code first before resuming the spawning (main) thread of the process.
The thread-creating code of your program itself is just a thread - it does not need to be distinguished from any thread it creates.
Automatic program termination after a thread ends will be most inconvenient in most settings (Imagine a multi-threaded program where one thread enters a non-recoverable error state while another thread performs a backup job). So while the code/language may lack overt syncing primitives, usually there still exist mechanisms to allow for a controlled thread termination.