Week 4 - Practical Exercise

Aims

Tasks

Exercise 1

Start a new directory and create a file thread_race.c whose main will take exactly one command line argument, a delay, much like the tutorial last week. Only this time have a global int variable called thread_delay and set this using the command line value (we’ll get rid of this soon enough, but for now…).

Exercise 2

Also produce a makefile that compiles your program. remember to use the right flags:

gcc -Wall  -pthread thread_race.c -o thread_race

Exercise 3

Once you have this working (not that it does much) declare a local long variable called shared_counter and set it to zero. We are going to create two threads, one that increments this variable, and one that decrements it. Both will also waste CPU time for a while by looping madly, similar to the way we did things last week.

Exercise 4

Now write two procedures:

void* increment_shared_counter(void *counter);
void* decrement_shared_counter(void *counter);

that do the following:

 for(i = 0; i < thread_delay; i++);

This should be in the body of the loop of course.

pthread_create(&up, NULL, increment_shared_counter, &shared_counter);
pthread_create(&down, NULL, decrement_shared_counter, &shared_counter);

the main thread should (in an infinite loop) print out the value of the shared counter, and then waste cpu time with a loop like that in both threads. What happens? Oh control C is useful here.

Exercise 5

OK so for the next part (I’ll not give so many hints) I want you to eliminate the need for the global variable thread_delay by passing in a pointer to a struct. Lecture 8 is a good source of ideas here:

This version should just be called race.c.

Enjoy ;) - Solutions will be available next week