CSE 451

Operating Systems

Spring 1998


Quiz #3

Distributed :  4/21/98 (Tuesday)
Due            :  4/23/98 (Thurday -- in the begining of the Section)

This quiz introduces you to thread programming. There are various thread packages which does thread management on most modern operating systems (including modern versions of Unix). The DEC Alphas (orcas and sanjuan) provide a package called pthreads. Every thread package provides basic operations like create and join. create creates a new thread which starts executing from a function given as parameter to the create() call. join waits for the thread mentioned in the join() call to complete. That is, the thread calling join blocks until the thread given as parameter to join() terminates.

It might be usefull to read section 4.5 of the book before you attempt the quiz.

Consider the following program, which uses DCE threads (a thread package which runs on the DEC Alphas):

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int global_counter = 0;

#define NUMBER_OF_ITERATIONS 1000000

void MyThreadFunction(char *name)
{
    int i;
    int local_counter = 0;

    for (i=0; i< NUMBER_OF_ITERATIONS; i++)
    {
        global_counter++;
        local_counter++;
    }

    printf("I am %s thread. (local_counter = %d, global_counter = %d)\n",
        name, local_counter, global_counter);
}

main()
{
    pthread_t t1, t2, t3;   /* Thread handles */
    pthread_addr_t status;  /* status returned by the threads */

    /* Creates three threads all executing the code in the function
       MyThreadFunction */
    pthread_create(&t1, pthread_attr_default, MyThreadFunction, "first");
    pthread_create(&t2, pthread_attr_default, MyThreadFunction, "second");
    pthread_create(&t3, pthread_attr_default, MyThreadFunction, "third");

    /* Waits for the threads to complete */
    pthread_join(t1, &status);
    pthread_join(t2, &status);
    pthread_join(t3, &status);
}

Compile and run the above program on the DEC Alphas. To compile the program use a command like:

cc  main.c -threads -o main

Note: DONOT use gcc.


Question:

Run the program multiple times.
Report your results.
Explain the results.

Change  NUMBER_OF_ITERATIONS to 1000
What change do you  observe.
Give a possible explanation.