为什么我要使用共享内存和单独的进程而不是std ::线程?
当讲师提到的shmget
作为反学通信的一个示例时,我正在观看有关操作系统的最新讲座系列。这个问题是关于“共享内存”和shmget
的亲戚。
什么是共享记忆
? “ rel =“ nofollow noreferrer”>此网页:
共享内存是附加到某些的额外记忆 地址空间供所有者使用。结果,所有这些 流程[,父母和孩子]共享相同的内存段 访问它。
与线程相比
线程已经具有共享的内存空间。以下是一个示例:
#include <iostream>
#include <thread>
struct SomeData {
int a;
int b;
int c;
};
void PrintC(SomeData* data_ptr) {
std::cout << (*data_ptr).c << "\n";
}
int main() {
SomeData data{ 4, -2, 18 };
std::thread c_printer(PrintC, &data);
std::cout << data.a << "\n";
c_printer.join();
return 0;
}
问题
如果程序员需要共享内存,为什么他们会使用单独的进程而不是单独的线程?
是共享内存(如shmget
之类的函数创建)只是实现线程的一种方法(例如,std :: thread
)?
是否有C ++标准库函数我应该期望在引擎盖下使用共享内存,或者仅适用于fork
新进程时共享内存?
I was watching a recent lecture series on Operating Systems when the lecturer mentioned shmget
as an example of interprocess communication. This question is about "shared memory" and relatives to shmget
.
What is shared memory?
According to this webpage:
A shared memory is an extra piece of memory that is attached to some
address spaces for their owners to use. As a result, all of these
processes[, parent and child,] share the same memory segment and have
access to it.
Compared to threads
Threads already have shared memory space. Here is an example:
#include <iostream>
#include <thread>
struct SomeData {
int a;
int b;
int c;
};
void PrintC(SomeData* data_ptr) {
std::cout << (*data_ptr).c << "\n";
}
int main() {
SomeData data{ 4, -2, 18 };
std::thread c_printer(PrintC, &data);
std::cout << data.a << "\n";
c_printer.join();
return 0;
}
The Questions
If the programmers needs shared memory, why would they use separate processes instead of separate threads?
Is shared memory (as created by functions like shmget
) just a way to implement threads (e.g., std::thread
)?
Are there C++ standard library functions I should expect to use shared memory under the hood, or is shared memory exclusively for when you fork
new processes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用子处理代替线程的优点是可以封装单独过程的内存。这适合隐私问题(考虑一种您正在处理包含私人信息的Web请求的情况),并且也出于正确的关注,因为一个过程的记忆不能由另一个过程任意修改。当然,如果您选择使用它,则无法完全实现此好处。请注意,共享内存不是相互处理通信的唯一形式。
线程的优点是:
在某些系统上,这可能是实现细节。但是从抽象的角度来看,这些是不同的概念。 C ++语言中没有“共享内存”或“过程”的概念。
An advantage of using subprocesses instead of threads is that the memory of separate processes can be encapsulated. This is good for privacy concerns (consider a case where you are handling a web requests that contains private information), and also for correctness concerns since the memory of one process cannot be arbitrarily modified by another. Of course, this benefit is not fully realised for the part of shared memory if you choose to use it. Note that shared memory is not the only form of inter process communication.
Advantages of threads are:
On some systems, this may be true as an implementation detail. But from abstract perspective, these are distinct concepts. There is no concept of "shared memory" or "process" in the C++ language.