2
$\begingroup$

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)

$\endgroup$
1
  • 3
    $\begingroup$ That would depend on what the termination conditions of the program are. Does it terminate when the thread containing main terminates? Or when the last spawned subthread terminates? If your question is specific to C, you should ask on Stack Overflow. $\endgroup$ Commented Mar 27, 2014 at 15:33

1 Answer 1

3
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.