进程VS线程:两个进程可以共享同一共享内存吗?可以有两个线程吗?

编程入门 行业动态 更新时间:2024-10-17 13:26:45
本文介绍了进程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线程:两个进程可以共享同一共享内存吗?可以有两个线程吗?

本文发布于:2023-11-17 02:36:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   进程   内存   两个   有两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!