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

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

问题描述

pthread和fork的基本区别是什么. 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()syscall,所以我猜 两者在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.

有人可以给出深入的解释吗?

Can someone give a deep explanation?

另请参阅相关的问题

推荐答案

但是在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天全站免登陆