1

I have two processes, A and B, that are using shared memory. I want process B to wait to use the shared memory until it is completely initialized by process A. To coordinate this, I am attempting to use a named semaphore.

// process A
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
(create and initialize shared memory here)
sem_post(s);
// process B
sem_t *s = sem_open(SNAME, O_CREAT|O_RDWR, 0644, 0);
sem_wait(s);
(load and use shared memory here)

However, if I start process A first, process B will get stuck at sem_wait. This does not make sense to me, because I would assume that the sem_post(s) in process A will increment the counter in the named semaphore for process B, too, since it seems to be "shared" in a way.

What is the easiest way to modify this code to make sure that process B will wait for process A to initialize the shared memory, without assuming that process B will start first?

3
  • sem_post increments the value and wakes waiting threads. Maybe use sem_getvalue in process B to see if the value has already been incremented. If it hasn't then you can sem_wait. (I'm not sure this really works across processes. There's a tiny window that can create a race condition.)
    – Ouroborus
    Commented Jul 5, 2022 at 6:47
  • I already used sem_getvalue to determine that executing sem_post in process A has no effect on the semaphore's counter in process B. I want to call sem_wait in process B, but the problem is that if process A executes sem_post first, then process B will sleep forever.
    – Solver
    Commented Jul 5, 2022 at 6:55
  • ???? I have never seen this behaviour with any semaphore. It breaks the P/V definition of a semaphore. If the semaphore has the unit posted by A, B should get that unit and run on. Commented Jul 5, 2022 at 9:10

1 Answer 1

-1

For some OS, there is specific mechanism for barrier and it would be advantage.

In general, there is also option to use mutex/exclusive area to protect a flag (variable) to indicate the initialization status. So instead of waiting OS to activate your task again, you just sleep and read the value. With this approach, the process order will not impact to the result.

2
  • Hi ThongDT. Thank you for the answer. This doesn't help me much, because I am already using semaphores instead of mutexes. Your answer doesn't clearly tell me why switching to a mutex approach from my semaphore approach would help. That being said, I did upvote your answer.
    – Solver
    Commented Jul 5, 2022 at 8:25
  • the problem comes from sem_wait(s) so you have to handle in different way. mutex is just to prevent access at the same time. you just need to have a share variable to indicate the initialize status.
    – ThongDT
    Commented Jul 5, 2022 at 9:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.