網頁

2011年1月9日 星期日

OS concept - Synchronization

Synchronization is an important concept in Operating System. Producer/Consumer and Reader/Writer are two examples of synchronization problems. The following is the sample codes for them. 

Producer and Consumer

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

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);
}

沒有留言:

張貼留言