What if you could do this?
pthread_create()
has to create a new stack for the new thread to use. If pthread_create()
copied the existing thread's old stack into a separate block of memory to create a new stack, then what would happen to local variables that point to other local variables? The local variables on the new stack would point to the old stack. When the thread using the old stack (the one that called pthread_create()
) returns or overwrites them, those variables start pointing to invalid data.
But what about fork()
? Why doesn't fork()
take a function pointer like pthread_create()
? Well, unlike pthread_create()
, the new thread of execution created by fork()
doesn't have to live in the same address space as the old thread of execution, because they are in separate processes. fork()
clones the parent process's virtual address space, stack, heap, and all. The child process's stack variables have the same virtual addresses as the corresponding variables in the parent process. So all of the pointers in the new child process continue to be valid*, no matter what the old parent process does with the memory.
* Nitpicker's corner: excluding pointers that were invalid to begin with, as well as memory that is deliberately shared