Binary
Binary

Reputation: 147

What happens to a running thread on return from main in C?

On linux, pthread (linux threads), what does happen to the running threads when returning from main (before the threads are finished)? When returning from main, the memory is dis-allocated so the threads should access unallocated memory. Does this cause the threads to exit?

I'm sure the threads are killed, but how does this actually happen?

Upvotes: 1

Views: 2292

Answers (2)

nos
nos

Reputation: 229058

I'm sure the threads are killed, but how does this actually happen?

Returning from main is the same as calling exit(). This means handlers established by atexit(), and any system cleanup handlers are run. Finally the kernel is asked to terminate the entire process(i.e. all threads).

(Note that this might cause issues if you have other threads running at that point, e.g. another thread accessing a global C++ objects right after the runtime calls their destructors.)

Upvotes: 2

luk32
luk32

Reputation: 16070

Well, threads operate under the process of main application (or other process but I assume you do not create another process, just threads). They share memory with it, and are the same process, so is system kills the process it automatically kills all threads. There is nothing more to it. A thread cannot exists without a process, so there is no option of accessing some disallocated memory, it just stops executing, and the memory is cleaned up on a process clean-up level.

And how it happens is obviously system dependent. E.g. Windows 95 did not free memory after a process ended, so if application had a memory leak, killing it didn't help. This had changed since then. Every system can handle it differently.

Upvotes: 1

Related Questions