进程VS线程:两个进程可以共享同一共享内存吗?可以有两个线程吗? [英] Process VS thread : can two processes share the same shared memory ? can two threads ?

查看:1182
本文介绍了进程VS线程:两个进程可以共享同一共享内存吗?可以有两个线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑了共享内存的整个概念之后,出现了一个问题:

After thinking about the the whole concept of shared memory , a question came up:

两个进程可以共享相同的共享内存段吗?两个线程可以共享相同的共享内存吗?

can two processes share the same shared memory segment ? can two threads share the same shared memory ?

经过一番思考之后,我几乎肯定两个进程可以共享同一个共享内存段,其中第一个是父级,第二个是子级,它是用fork()创建的,但是两个线程呢?

After thinking about it a little more clearly , I'm almost positive that two processes can share the same shared memory segment , where the first is the father and the second is the son , that was created with a fork() , but what about two threads ?

谢谢

推荐答案

两个进程可以共享相同的共享内存段吗?

can two processes share the same shared memory segment?

是,不是.通常在现代操作系统中,当另一个进程从头开始 fork 时,它们共享相同的进程在所有页面上都设置了写时复制的存储空间.对任何读写内存页进行的任何更新都会导致对该页进行复制,因此将有两个副本,并且该内存页将不再在父进程和子进程之间共享.这意味着将仅共享只读页面或未写入的页面.

Yes and no. Typically with modern operating systems, when another process is forked from the first, they share the same memory space with a copy-on-write set on all pages. Any updates made to any of the read-write memory pages causes a copy to be made for the page so there will be two copies and the memory page will no longer be shared between the parent and child process. This means that only read-only pages or pages that have not been written to will be shared.

如果一个进程没有从另一个进程中派生出来,则它们通常不共享任何内存.一个例外是,如果您正在运行同一程序的两个实例,则它们可能共享代码,甚至可能是静态数据细分,但不会共享其他页面.

If a process has not been forked from another then they typically do not share any memory. One exception is if you are running two instances of the same program then they may share code and maybe even static data segments but no other pages will be shared.

也有特定的内存映射调用共享同一内存段.该调用指定映射是只读的还是读写的.如何做到这一点取决于操作系统.

There are also specific memory-map calls to share the same memory segment. The call designates whether the map is read-only or read-write. How to do this is very OS dependent.

两个线程可以共享相同的共享内存吗?

can two threads share the same shared memory?

当然.通常,多线程进程内部的所有内存都由所有线程共享".这通常是线程的定义,因为它们都在同一内存空间中运行.

Certainly. Typically all of the memory inside of a multi-threaded process is "shared" by all of the threads. That is usually the definition of threads in that they all are running within the same memory space.

线程还具有. 共享此缓存的内存,并根据同步操作将对内存页面的更新刷新到中央存储中.

Threads also have the added complexity of having cached memory segments in high speed memory tied to the processor/core. This cached memory is not shared and updates to memory pages are flushed into central storage depending on synchronization operations.

这篇关于进程VS线程:两个进程可以共享同一共享内存吗?可以有两个线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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