Home > database >  Is shared memory in POSIX protected against race conditions?
Is shared memory in POSIX protected against race conditions?

Time:08-24

I have two processes written in C running on Linux that access shared memory. Both processes have something along the lines of

int shm_fd = shm_open(NAME, O_RDWR, 0666);
ftruncate(shm_fd, sizeof(shm_data_struct));
struct shm_data_struct* shm_ptr = (struct shm_data_struct*)mmap(0, sizeof(struct shm_data_struct), PROT_WRITE, MAP_SHARED, shm_fd, 0);

Both processes can read and write from the struct in shared memory. My question is: does POSIX automatically provide any sort of protection from race conditions or do you always have to add in your own semaphore/mutex in this scenario?

CodePudding user response:

You don't use any library or system call to access the memory once it's set up. It's accessed directly by CPU instructions just like any other memory. That's because it is memory just like any other memory.

The memory in question is shared between threads in different processes. But the fact that the threads are in different processes is irrelevant. Everything that applies to sharing memory between threads in a single process applies the sharing memory between threads in different processes: You need memory barriers and some form of synchronization.

  • Related