Jordan Scales
Jordan Scales

Reputation: 2717

Managing a mutex in shared memory

I'm attempting the simple task of creating a mutex in shared memory. I have the following code to declare a section of shared memory, and attach it to an int*.

int *mutex;

// allocate shared memory for mutex
if ((shmid2 = shmget(IPC_PRIVATE, 4, IPC_CREAT | 0666)) < 0) {
  printf("Could not allocate shared memory for mutex: %d.\n", errno);
  exit(errno);
}

if ((mutex = shmat(shmid2, NULL, 0)) == (int*)-1) {
  printf("Could not attach shared memory for mutex: %d\n", errno);
  exit(errno);
}

// set the mutex to one
mutex[0] = 1;

Now, I attempt to define a critical section, surrounded by locking and unlocking the mutex. (Inside of one of many child processes).

while (*mutex == 0) ;
mutex[0] = 0;

// critical section

...

// end critical section

mutex[0] = 1;

However, I'm finding that this technique does not work, and two child processes can enter the critical section simultaneously, without much issue (it happens very often). So I'm wondering what I can do to fix this, without the use of pthreads.

Upvotes: 1

Views: 1536

Answers (1)

user149341
user149341

Reputation:

Your options are:

  1. Use POSIX semaphores instead of trying to implement them yourself with shared-memory spinlocks. See the documentation for semop (2) and related functions for details.

  2. If you must use shared-memory semaphores, you will need to use an atomic compare/exchange. Otherwise, two processes can both simultaneously see *mutex == 0 and set it to 1 at the same time, without "noticing" that the other process is doing the same thing.

Upvotes: 5

Related Questions