Home CS439

CS439: Principles of Computer Systems

Homework 3, Part 1

Due in Section on Friday, February 12, 2016

Part 1 of the homeworks must be completed before section and brought to section. Please refer to the homework turnin instructions.

  1. 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 new 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. Notice that to compile code that uses pthreads you need to include the -pthread flag.

  2. 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.
  3. 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.
  4. Compare and contrast user threads and kernel threads.
  5. 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?