Reputation: 3345
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".
Upvotes: 24
Views: 11140
Reputation: 62661
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.
Upvotes: 13
Reputation: 5716
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.
Upvotes: 14
Reputation: 5205
Here is the source of pthread.c. This may help you answer your question.
Upvotes: 4