user589321
user589321

Reputation: 109

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

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?

Upvotes: 2

Views: 3765

Answers (1)

eerorika
eerorika

Reputation: 238351

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

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:

  • They can be used through a standard API.
  • Their creation has potentially less cost. The difference in cost varies from slight (Linux) to significant (Windows). Although, significance is relative. It won't matter for a long running process that runs constant number of processes.

Is shared memory (as created by functions like shmget) just a way to implement threads (e.g., std::thread)?

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.

Upvotes: 4

Related Questions