I am experienced at multithreaded programming in Java and C#, and am starting to learn how to do it in C on Linux. I "grew up" in the programming sense on Linux, so I understand it's memory philophy, process handling, etc. at a high level.
My question is not how to do threading. I would like to know how pthread actually does it. Does it fork a process and handle your interprocess communication for you somehow? Or does it just manage the address space? I want nitty-gritty details :) Googling has only produced "how to do it" questions, not "how it works".
The details are probably too complex to really get into (without posting a link to the glibc source code), but I can give you better things to look up:
Pthread uses sys_clone() to create new threads, which the kernel sees as a new task that happens to share many data structures with other threads.
To do synchronization, pthread relies heavily on futexes in the kernel.
On Linux, both fork()
and ptrheads use the same syscall clone()
, which creates a new process. The difference between them is simply the parameters they send to clone()
, when creating a new thread, it simply makes both processes use the same memory mappings.
Remember, in Linux (and other modern Unixes), memory mappings, stacks, processor state, PIDs, and others are orthogonal features of a process; so you can create a new process with just a new stack and process state (sharing everything else), and call it a thread.
Here is the source of pthread.c. This may help you answer your question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With