- Suppose that your program has a series of queued jobs that are processed by several concurrent threads. The queue of jobs is represented by a linked list of struct job objects. http://siber.cankaya.edu.tr/SystemsProgramming/cfiles/job-queue1.cjob-queue1.c (see Fig. 8)
Figure 8:
Thread Function to Process Jobs from the Queue
|
- Now suppose that two threads happen to finish a job at about the same time, but only one job remains in the queue. By unfortunate coincidence, we may have two threads executing the same job.
- To make matters worse, one thread will unlink the job object from the queue, leaving job_queue containing null. When the other thread evaluates job_queue-next, a segmentation fault will result.
- This is an example of a race condition. Under lucky circumstances, this particular schedule of the two threads may never occur, and the race condition may never exhibit itself. Only under different circumstances, may the bug exhibit itself.
- To eliminate race conditions, you need a way to make operations atomic.
- In this particular example, you want to check job_queue; if it s not empty, remove the first job, all as a single atomic operation.
2006-03-24