Synchronization
  • Introduction
  • Race Condition
    • Too Much Milk Problem
  • Mutual Exclusion
    • Shared Output
  • Semaphore in C
  • Too Much Milk: Use semaphore
  • Shared Output: Use semaphore
  • Traffic Control Problem
  • Traffic Control: Solution
  • Shared Memory
Powered by GitBook
On this page

Was this helpful?

  1. Mutual Exclusion

Shared Output

PreviousMutual ExclusionNextSemaphore in C

Last updated 1 month ago

Was this helpful?

From the introduction, mutual exclusion restricts only one process to enter a critical section.

process1.c and process2.c are two processes that need to display their outputs on the standard error. To ensure the output is right, these two processes should access the standard error exclusively. That is to say, one process should wait until the other process occupying the standard error finishes its display. Otherwise, the output may be confusing as shown in the figure. We can use semaphore to ensure mutual exclusion. The result is shown in figure 2.

Comment out semaphore-related codes, run these two programs (process1.c, process2.c) and see what happens.

/*process1.c*/
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {

    char *c = "This is CSCI3150--An operating system course.\n";
    // specify no buffering for stderr
    setbuf(stderr, NULL);

    while (*c != '\0') {
        fputc(*c, stderr);
        c++;
        sleep(1);
    }
    return 0;
}
/*process2.c*/
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {

    char *c = "This is CSCI3150--An operating system course.\n";
    // specify no buffering for stderr
    setbuf(stderr, NULL);

    while (*c != '\0') {
        fputc(*c, stderr);
        c++;
        sleep(rand() % 2 + 1);
    }
    return 0;
}