CS360 Midterm -- May 2, 2002


Question 5

Behold the program to the right.

Part 1: This program outputs a string of 25 digits from 0 to 4. For each assertion below, state whether it is always true, always false, or true only part of the time.

  • Assertion 1: The string starts with two zeros.
  • Assertion 2: The string starts with three zeros.
  • Assertion 3: The string starts with four zeros.
  • Assertion 4: The string starts with five zeros.
  • Assertion 5: The string ends with a four.
  • Assertion 6: The string ends with two fours.
  • Assertion 7: The string ends with three fours.
  • Assertion 8: The string ends with the characters '33434'.
  • Assertion 9: The string ends with the characters '43434'.
  • Assertion 10: No 3 may be printed until three 2's have been printed before it.
  • Assertion 11: A 3 is printed before two 2's have been printed.
  • Assertion 12: The string ends with the characters '01234'.
Hint: Figure out exactly what the program does first -- then answering each assertion should be quick and easy.

Part 2: It is possible for a thread to hang forever. To make this clearer, put a sleep(random()%25) at the comment HERE. Explain how a thread could hang forever.

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

pthread_mutex_t m[5];
pthread_cond_t c[5];
int n[5];

void *thread(void *v)
{
  int i;

  for (i = 0; i < 5; i++) {
    sleep(random()%10);
    pthread_mutex_lock(m+i);
    while (i > 0 && n[i-1] < 3) {
       /* HERE */
       pthread_cond_wait(c+i, m+i);
    }
    printf("%d", i); fflush(stdout);
    n[i]++;
    if (i < 5) pthread_cond_signal(c+i);
    pthread_mutex_unlock(m+i);
  }
}

main()
{
  int i;
  pthread_t tids[5];
  void *retval;

  srandom(time(0));
  for (i = 0; i < 5; i++) {
    pthread_mutex_init(m+i, NULL);
    pthread_cond_init(c+i, NULL);
    n[i] = 0;
  }

  for (i = 0; i < 5; i++) {
    pthread_create(tids+i, NULL, 
           thread, (void *) NULL);
  }

  for (i = 0; i < 5; i++) {
    pthread_join(tids[i], &retval);
  }
  printf("\n");
}