CS439: Principles of Computer Systems

Homework 2

(Source: Alison Norman.)

Due: 9:00 PM Monday, January 28, 2013

Homeworks will be submitted electronically. Please refer to the homework turnin instructions.

  1. Compare and contrast user threads and kernel threads.
  2. When executing system or library calls from multi-threaded code, it is important to know which calls are re-entrant and which are not.
    • What is the meaning of re-entrant?
    • How does a re-entrant call behave differently from a call that is not re-entrant?
    • Why is this an important consideration for multi-threaded code?
  3. A standardized C language threads programming interface has been developed for UNIX systems, IEEE POSIX 1003.1c. Thread implementations that adhere to this standard are known as POSIX threads, or Pthreads. Using Pthreads, write a C program that creates three threads and assigns each of them a number. Each thread should print the numbers 1-10, one per line, with its number beginning the line, so that the beginning output from thread 1 would look like the following:
    1: 1
    1: 2
    1: 3
    
    The original thread should wait for the new threads to finish and then print a statement notifying the user that the application is finished.

    Explain the output. Turn in your code, output, and explanation.

    Hint: man 7 pthreads provides an overview of pthreads and should help you get started.

  4. Given the following pseudocode:
    int i = 0;
    
    int main(void)
    { 
       fork();
    
       if(/*CHILD*/)
       {
          i = i - 1;
          return SUCCESS;
       }
       if(/*PARENT*/)
       {
          i = i + 1;
          wait for child to terminate;
    
          printf("i = %d\n", i);
       }
    }
    

    • What is the output? Describe in detail why it is that way.
    • Are there other possible outputs? Why or why not? If so, give another example of what the printed values of ``i'' might be and explain how to force the program to execute the same way each time.
  5. Now consider this pseudocode involving kernel threads:
    int i = 0;
    
    void thread1(void *)
    {
       i = i - 1;
    }
    
    void thread2(void *)
    {
       i = i + 1;
    }
    
    int main(void)
    {
       createThread(thread1);
       createThread(thread2);
    
       /* wait for thread 1 and thread 2 to end */
    
       printf("i = %d\n", i);
    }
    
    • What is the output? Describe in detail why it is that way.
    • Are there other possible outputs? Why or why not? If so, give another example of what the printed values of ``i'' might be and explain how to force the program to execute the same way each time.