Skip to content

Multi threaded Programming: Review Questions

Lawrence Angrave edited this page Nov 25, 2015 · 21 revisions

(Todo - move this question to another page) What mistake did the programmer make in the following code? Is it possible to fix it i) using heap memory? ii) using global (static) memory?

static int id;

char* next_ticket() {
  id ++;
  char result[20];
  sprintf(result,"%d",id);
  return result;
}

Is the following code thread-safe? Redesign the following code to be thread-safe. Hint: A mutex is unnecessary if the message memory is unique to each call.

static char message[20];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZAER;

void format(int v) {
  pthread_mutex_lock(&mutex);
  sprintf(message,":%d:",v);
  pthread_mutex_unlock(&mutex);
  return message;
}

Write a mathematical expression for the number of "B" characters that will be printed by the following program. Assume a,b,c,d are small positive integers. Your answer may use a 'min' function that returns its lowest valued argument.

unsigned int a=...,b=...,c=...,d=...;

void* func(void* ptr) {
  char m = * (char*)ptr;
  if(m == 'P') sem_post(s);
  if(m == 'W') sem_wait(s);
  putchar(m);
  return NULL;
}

int main(int argv, char**argc) {
  sem_init(s,0, a);
  while(b--) pthread_create(&tid,NULL,func,"W"); 
  while(c--) pthread_create(&tid,NULL,func,"P"); 
  while(d--) pthread_create(&tid,NULL,func,"W"); 
  pthread_exit(NULL); 
  /*Process will finish when all threads have exited */
}
Clone this wiki locally