3

I have a bit of a problem at how to synchronize 2 processes. First process must create a shared memory, then wait for the second process to fill the shared memory and signalize it back to the first process. I don't know how to make the first process wait.

Here is a pseudocode of how my processes look like:

Process1:

create shared memory
create a semaphore
wait for the second process /* this part i dont know how to write */
output the shared memory

Process2:

get shared memory id
get the semaphore id
wait();
fill the shared memory 
signalize();
1
  • create shared memory and semaphores in process 2 and get shared memory and semaphore id in process1, and do a sem_wait in process1 for the shared memory and do a sem_post in process2 after you copied the data into the shared memory.
    – John
    Dec 10, 2013 at 12:50

2 Answers 2

3

You are correct so far.

As you mentioned in your question you are using semaphore that is the answer to your question.

In posix semaphore api, you have sem_wait() which will wait until value of the semaphore count is zero once it is incremented using sem_post from other process the wait will finish.

In this case you have to use 2 semaphores for synchronization.

process 1 (reader)
sem_wait(sem1);
.......

.......
sem_post(sem2);

process 2(writer)
sem_wait(sem2);
.......
.......
sem_post(sem1);

In this way you can achieve synchronization in shared memory.

0

This is hint and not an complete answer. Use condition variables. See https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables, that explains how it works. You can work out the solution from there.

2
  • Isn't conditional variables suppose to work only with threads? Or Am I missing something?
    – Jay
    May 27, 2012 at 9:42
  • Ok I solved it in a different way. We wait for the other process when we set the value of the sem_op=0;.
    – Kajzer
    May 27, 2012 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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