Home:ALL Converter>Why would I use shared memory and separate processes instead of std::thread?

Why would I use shared memory and separate processes instead of std::thread?

Ask Time:2022-05-05T02:53:54         Author:user589321

Json Formatter

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?

Author:user589321,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72118099/why-would-i-use-shared-memory-and-separate-processes-instead-of-stdthread
yy