Jelly
Jelly

Reputation: 4532

Take turns using semaphores

This might be a trivial problem but I couldn't find any clear answer. How can you make two processes take turns using only semaphores? I don't want to use sleep or other IPCs. The result should be something like:

Process 1 did something
Process 2 did something
Process 1 did something
Process 2 did something
Process 1 did something
Process 2 did something
Process 1 did something
Process 2 did something

Upvotes: 1

Views: 627

Answers (1)

BartoszKP
BartoszKP

Reputation: 35911

You need two semaphores, one for each process, lets say S1 and S2. The sequence of interaction between processes P1 and P2 would be as follows:

  1. P1 waits on S1, P2 waits on S2.
  2. Lets say that initially S1 is open, S2 closed.
  3. P1 does its work - closes S1, opens S2, and waits on S1
  4. P2 does its work - closes S2, opens S1, and waits on S2
  5. start over from 3.

Upvotes: 2

Related Questions