Synchronization

Producer and Consumer

int buf[N], in = 0, out = 0;
sem filledslots = 0, emptyslots = N, mutex = 1;
 
Producer()
{
    wait(emptyslots);
 
    wait(mutex);
 
    Produce(buf[in]);
    in = (in + 1) % N;
 
    wait(mutex);
 
    signal(filledslots);
}
 
Consumer()
{
    wait(filledslots);
 
    wait(mutex);
 
    Consume(buf[out]);
    out = (out + 1) % N;
 
    wait(mutex);
 
    signal(emptyslots);
}

Reader and Writer

int n = 0;
sem mutex = 1, RW = 1;
 
Reader()
{
    wait(mutex);   // lock reader
    n++;
    if (n == 1)
        wait(RW);  // lock first reader when there is a writer
    signal(mutex);
 
    Read();
 
    wait(mutex);
    if (n == 1)
        signal(RW);
    n--;
    signal(mutex);
}
 
Writer()
{
    wait(RW);      // wait if at least one reader is reading
 
    Write();
 
    signal(RW);
}

Dining Philosopher

sem p[n] = 1, mutex = 1;
 
Philosopher(int i)
{
    while (1) {
        Think();
 
        wait(mutex);       // need to get 2 forks at the same time
 
        wait(p[i]);        // wait for pi
        PickupFork(i);
        wait(p[(i + 1) % n]);   // wait for pi+1
        PickupFork((i + 1) % n);
 
        signal(mutex);
 
        Eat();
 
        PutDownFork(i);
        signal(p[i]);
        PutDownFork((i + 1) % n);
        signal(p[(i + 1) % n]);
    }
}

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License