MP01

Generating a Race Condition and Eliminating It


Introduction

In this assignment you will be using a test-and-set instruction to eliminate a race condition in a multi-threaded program. The test-and-set instruction is an instruction used to both test and (conditionally) write to a memory location as part of a single atomic (i.e. non-interruptible) operation. This means setting a value, but first performing some test (such as, the value is equal to another given value). If the test fails, the value is not set. If multiple processes may access the same memory, and if a process is currently performing a test-and-set, no other process may begin another test-and-set until the first process is done. 

The test-and-set instruction is used as the basis for many of the control elements that are used in concurrent and parallel programming. Constructs such as semaphores, critical sections and mutexes are implemented with the aid of test-and-set instructions.

The Problem

Some multithreaded code is provided here. This code uses several threads to update the value of a global variable called sharedMemory. Download the code and create a project with it.

You will notice that when you run the code with multiple threads (up to 64), the value that ends up in sharedMemory appears to be correct. The code as written will in fact exhibit a race condition. Due to the way the threads are invoked, the race condition may be hidden by the order of thread execution.

Your first task is to modify the code in the myThread function, so that we can clearly see that a race condition occurs. (HINT: combinations of local variables and the Sleep function will make the race condition apparent).

The solution to this part should be contained in a project called MP01a.

You next task is to use some code available here that uses a test-and-set instruction to implement a semaphore. Use the semaphore with the MP01a code to eliminate the race condition.

The solution to this part should be contained in a project called MP01b.

What to turn in

Zip up both projects (MP01a and MP01b) into a file called MP01.zip. Submit this to the homework submission system.