Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

Difference between pthread and fork on gnu/Linux

What is the basic difference between a pthread and fork w.r.t. linux in terms of implementation differences and how the scheduling varies (does it vary ?)

I ran strace on two similar programs , one using pthreads and another using fork, both in the end make clone() syscall with different arguments, so I am guessing the two are essentially the same on a linux system but with pthreads being easier to handle in code.

Can someone give a deep explanation?

EDIT : see also a related question

question from:https://stackoverflow.com/questions/5514464/difference-between-pthread-and-fork-on-gnu-linux

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C there are some differences however:

fork()

  • Purpose is to create a new process, which becomes the child process of the caller

  • Both processes will execute the next instruction following the fork() system call

  • Two identical copies of the computer's address space,code, and stack are created one for parent and child.

Thinking of the fork as it was a person; Forking causes a clone of your program (process), that is running the code it copied.


pthread_create()

  • Purpose is to create a new thread in the program which is given the same process of the caller

  • Threads within the same process can communicate using shared memory. (Be careful!)

  • The second thread will share data,open files, signal handlers and signal dispositions, current working directory, user and group ID's. The new thread will get its own stack, thread ID, and registers though.

Continuing the analogy; your program (process) grows a second arm when it creates a new thread, connected to the same brain.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...