Home CS439

CS439: Principles of Computer Systems

Homework 4, Part 1

Due: 8:45a Friday, February 20, 2015

Part 1 of the homeworks must be submitted electronically. Please refer to the homework turnin instructions.

  1. What does the function pthread_detach() do? What default behavior of threads does it alter? When might it be useful?

  2. Given the following pseudocode:
    int sharedData;
    void* total(){
    	int i;
            for(i = 0; i < 100; i++)
                    sharedData = sharedData + 1;
    int main(){
            sharedData = 0;
            // start running 2 threads executing total() concurrently and wait for them to finish execution
            pthread_t thread[2];
            int i;
            for(i = 0; i < 2; i++)
                    pthread_create(&thread[i], NULL, total, NULL);
            for(i = 0; i < 2; i++)
                    pthread_join(thread[i], NULL);
            printf("%d\n", sharedData);
            return 0;

    1. On a single processor machine, what are possible outputs of this program?
      Determine both the lower bound and the upper bound of the output of this program.
      Justify your answer.

    2. Solve the above problem if we run m concurrent threads instead of two threads.
  3. Compare and contrast monitors and semaphores. What is an appropriate use of each?

  4. Consider the following program fragment:
    if(a > 0)
    if(b < 0 && a <= 0)
    else if(b >= 0 && a > 0)

    s1, s2, s3 and s4 are semaphores initialized to 1. All variables are automatic (on the stack). Now, consider two threads running this fragment of code simultaneously, can there be a deadlock? Why, or why not?

  5. You need two Hydrogen atoms and one Oxygen atom to make water. Using semaphores, write a solution that generates water whenever the right resources are available. You must have three functions: one to generate Oxygen, one to generate Hydrogen, and one to generate water. Assume the three methods may be executed by any number of threads concurrently.
  6. Solve the water problem using monitors.