Search code examples
multithreadingprocessoperating-systemshared-memory

Process VS thread : can two processes share the same shared memory ? can two threads?


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?

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?

Thanks


Solution

  • can two processes share the same shared memory segment?

    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. Another is how some operating systems allow applications to share the code pages for dynamic libraries that are loaded by multiple applications.

    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 except for some relatively small stack spaces which are per-thread. 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.