World's most popular travel blog for travel bloggers.

If a thread containing main terminates, can another thread do anything?

, , No Comments
Problem Detail: 

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)

Asked By : y0n1

Answered By : collapsar

While the details will depend on the actual thread model of your thread library (eg. pthreads, the POSIX thread library), some general observations hold.

  1. 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.

  2. The thread-creating code of your program itself is just a thread - it does not need to be distinguished from any thread it creates.

  3. 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.

Best Answer from StackOverflow

Question Source :

3200 people like this

 Download Related Notes/Documents


Post a Comment

Let us know your responses and feedback