gnu/Linux 上 pthread 和 fork 的区别 [英] Difference between pthread and fork on gnu/Linux

查看:26
本文介绍了gnu/Linux 上 pthread 和 fork 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pthread 和 fork w.r.t. 之间的基本区别是什么?在 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 ?)

我在两个类似的程序上运行了 strace,一个使用 pthreads,另一个使用 fork,最后都使用不同的参数使 clone() 系统调用,所以我猜两者在 linux 系统上基本相同,但 pthreads 更容易在代码中处理.

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.

谁能给个深刻的解释?

另见相关问题

推荐答案

在 C 中有一些差异:

In C there are some differences however:

fork()

  • 目的是创建一个新进程,成为调用者的子进程

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

两个进程都会执行fork()系统调用之后的下一条指令

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!)

第二个线程将共享数据、打开文件、信号处理程序和信号处置、当前工作目录、用户和组 ID.不过,新线程将获得自己的堆栈、线程 ID 和寄存器.

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.

这篇关于gnu/Linux 上 pthread 和 fork 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆