Tuesday, February 23, 2010

Race condition and Deadlock

 

A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable. Then the first thread and second thread perform their operations on the value, and they race to see which thread can write the value last to the shared variable. The value of the thread that writes its value last is preserved, because the thread is writing over the value that the previous thread wrote.

The typical solution to a race condition is to ensure that your program has exclusive rights to something while it's manipulating it, such as a file, device, object, or variable. The process of gaining an exclusive right to something is called locking.

A deadlock occurs when two threads each lock a different variable at the same time and then try to lock the variable that the other thread already locked. As a result, each thread stops executing and waits for the other thread to release the variable. Because each thread is holding the variable that the other thread wants, nothing occurs, and the threads remain deadlocked.

Deadlock Prevention

1. Remove mutual exclusion – no process should have exclusive access to a resource
2. Process should acquire all required resources before starting
3. By releasing resources after a certain amount of time
4. By assigning precedence to resources, so process an only try to acquire lower precedence resource

No comments: