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?