Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does pthread work?

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

like image 971
Michael K Avatar asked Jan 31 '11 19:01

Michael K


3 Answers

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.

like image 114
Karmastan Avatar answered Dec 07 '22 14:12

Karmastan


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.

like image 38
Javier Avatar answered Dec 07 '22 13:12

Javier


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

like image 34
David Weiser Avatar answered Dec 07 '22 13:12

David Weiser