next up previous
Next: Mutual Exclusion Up: XINU Processes and Previous: Shared Memory in

Synchronization and Semaphores

Assume it is required that the consumer print all the numbers produced by the producer. Does the above program achieve this goal?

The answer, surprisingly, is no. While execution of the producer and the consumer is interleaved, no guarantees are made about the relative execution speeds of the two processes, which the operating system is free to choose. Thus the programmer can make no assumptions about the way in which processor time is allocated to each process.

XINU provides semaphores to synchronize processes. A semaphore consists of an integer value, initialized when the semaphore is created. The system call wait decrements the semaphore and causes the suspended process to delay if the result is negative. Signal performs the opposite action, incrementing the semaphore and allowing a waiting process to continue. Semaphores are created dynamically with the call screate, which takes the initial count as an argument, and returns an integer by which the semaphore is known.

The following program illustrates the use of semaphores to achieve our goal of printing every value produced:

int n = 0;

main()
{
    int prod2(), cons2();
    int produced, consumed;
    consumed = screate(0);
    produced = screate(1);
    resume( create(cons2, 200, 20, "cons", 2, consumed, produced) );
    resume( create(prod2, 200, 20, "prod", 2, consumed, produced) );
}

prod2(consumed, produced)
{
    int i;

    for( i=1; i<=2000; i++ ) 
    {
        wait(consumed);
        n++;
        signal(produced);
    }
}

cons2(consumed, produced)
{
    int i;

    for ( i=1; i<=2000; i++) = 
    {
        wait(produced);
        printf("n is %d", n);
        signal(consumed);
    }
In the above example, two semaphores `consumed' and `produced' are created by calls to screate., The producer waits before the consumer prints a value of `n'. Likewise, the consumer prints a new value of `n' only after it has been incremented by the producer. Thus the consumer prints all values of n from 0 through 1999.

Prasun Dewan
Tue Jan 13 12:23:19 EST 2004