Sample questions for the midterm

  1. Consider the following code:
       if (0==fork()) {
          printf("Child\n");
       }
       printf("Parent\n");
    
    How many times is "Parent" printed? Why?

    "Parent" is printed twice - one by the parent and the other by the child. The child first executes the "if" part and then the execution falls through.

  2. Why should the TSL instruction be atomic to ensure mutual exclusion?

    If the execution of TSL is not atomic, the checking process can be preempted between testing and setting the lock. If another process tests the lock in between, it will also enter the critical region.

  3. Consider the following program.
        semaphore mutex=1; /* binary semaphore */
        down(mutex);
        down(mutex);
    
    By the normal definition of binary semaphores, this results in deadlock. But in this case, we want to allow multiple downs by the same process. Define the operations down and up permit multiple locks bt the same process without deadlock.

    The new definition requires that if a process already holding the lock tries to lock it again, the locking should succeed. This requires recoding the PID of the process holding the lock. If the same process tries to lock the mutex again, it succeeds. If a process with a different PID tries locking, it is blocked.

    The system should also keep a count of the number of times the same process locks the mutex. The mutex should be unlocked the same number of times before it is released.

  4. Describe how message passing can be used to implement semaphores.

    See page 55 of Tanenbaum.

  5. What is a monitor? What are the advantages of using monitors?

    A monitor is a programming language construct for mutual exclusion. The compiler recognizes monitor procedures and automatically generates code for mutual exclusion.

  6. Is the following code thread-safe? Why?
    // return unique id
    int returnId(void) {
       static int id=-1;
       id++;
       return id;
    }
    

    The above code is not thread-safe. If multiple threads execute returnId, then the value of id can get inconsistent. (One thread increments id, gets preempted, another thread increments id, and now the first thread returns the incorrect value.)

  7. Assume the freelist configuration shown below:
      10K, 4K, 20K, 18K, 7K, 9K, 12K, 15K
    
    For the sequence of requests
       12K, 10K, 9K
    
    What is the allocation under first fit, best fit, worst fit, and next fit?
    First fit: 20K, 10K, 18K
    Best fit: 12K, 10K, 9K
    Worst fit: 20K, 18K, 15K
    Next fit: 20K, 18K, 9K