23

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".

Michael K
  • 3,297
  • 3
  • 25
  • 37

3 Answers3

13

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:

  1. 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.

  2. To do synchronization, pthread relies heavily on futexes in the kernel.

Karmastan
  • 5,618
  • 18
  • 24
  • +1: just adding that `fork()` uses the same syscall but the new task shares less structures with the parent. – Javier Jan 31 '11 at 21:34
12

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.

Javier
  • 60,510
  • 8
  • 78
  • 126
3

Here is the source of pthread.c. This may help you answer your question.

David Weiser
  • 5,190
  • 4
  • 28
  • 35