1

I am sharing some memory (created with shm_open where I map different "regions" with mmap) across multiple processes. I am using named semaphores to synchronize accesses to that memory.

I have a region in that memory that is read-only (it has been set by the process that creates the shared memory object). Do I still need to use mutexes to let the processes read that region? If that region can be read concurrently I can drop named semaphores and share unnamed semaphores instead.

The question is similar to what asked here but maybe the OP was not clear enough.

ntd
  • 7,372
  • 1
  • 27
  • 44
  • 2
    As long as the shared memory is set before any read only access and never changed after that intialization, you can safely to concurrent reads. – Serge Ballesta Jul 12 '17 at 09:40
  • 1
    Also see the "Single Writer, Multiple Reader" pattern. For example, [Synchronization for multiple readers, single writer?](https://stackoverflow.com/q/618164/608639), [How to make a multiple-read/single-write lock from more basic synchronization primitives?](https://stackoverflow.com/q/27860685/608639) and [Lock free multiple readers single writer](https://stackoverflow.com/q/909443/608639). – jww Jul 13 '17 at 08:11
  • Possible duplicate of [Mutex locking when shared memory is only read](https://stackoverflow.com/questions/21586802/mutex-locking-when-shared-memory-is-only-read) – ntd Jul 19 '17 at 11:55

1 Answers1

1

According to multiple sources, reading the same memory seems to not introduce race conditions, so it could be done without locking. I have a couple of systems running from months with one process writing (with a global lock) and two other processes continuosly reading the same shared memory and I have never had issues.

ntd
  • 7,372
  • 1
  • 27
  • 44
  • If I have one process that writes to a shared memory, and other processes that read from that memory, do I need to lock the memory while writing, or it's an atomic operation? – Rony Tesler Jan 09 '22 at 18:10
  • No to both your questions: you do not need to lock the memory and it is not an atomic operation. – ntd Feb 11 '22 at 07:59
  • why don't I need to lock? If I don't lock, and it's not atomic, one process can read when another process is in the middle of writing, no? – Rony Tesler Feb 11 '22 at 12:55
  • In the situation described above, one process writes to the shared memory **before** sharing it. If you need to write concurrently you need locks, but the question was all about reading concurrently. – ntd Feb 11 '22 at 22:04