Race condition

From Rosetta Code
Revision as of 03:16, 24 October 2007 by MikeMol (talk | contribs) (Created page)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

A race condition is a condition where the outcome of an instruction depends on interference from another thread or process. Commonly, this interference comes in the form of two processes depending on or manipulating the same piece of memory.

Reasons

Shared objects

Most popular platforms perform multitasking, where multiple threads of code run on the same computer. These threads may be their own processes, or they may be part of a larger program. In addition, these threads may share the same CPU core, or there may be multiple cores (or CPUs) available.

When a thread refers to a piece of memory (i.e. an object), they may make decisions based upon its contents, and it might assume that that object will not change between the time it looks at it and the time when it carries out an action based on that glance. Take this C++ example:

CObject* pObj = GetSharedObject();
if ( pObj->Available() ) // Check to see if the object is available
{
     DoSomethingWith( pObj ); // Use the object
}

In this code, pObj points to an object (returned by GetSharedObject) that may be shared with other threads. Let's assume for the moment that another thread has also called GetSharedObject(), and received a pointer to the same object we're working with.

Because of the nature of multitasking, it's possible that the second thread might have accessed the shared object after we checked to see if the object was available, but before we did something with that object. And it's possible that what the second thread did with our shared object will make our DoSomethingWith() method fail.

Inconsistency

While it's possible that another thread with access to our object changed it between the times when we checked its availability and when we attempted to use it, it's also possible that the second thread operated on the shared object before or after our code, in which case DoSomethingWith() likely wouldn't have failed. Whether or not our code fails depends on the timing of when the two threads accessed the same object. Since timing is rarely consistent, the failure of our code (or any code subject to race conditions) can be inconsistent and difficult to trace.


This page is a stub. It needs more information! You can help Rosetta Code by filling it in!

Solutions

This page is a stub. It needs more information! You can help Rosetta Code by filling it in!