Race condition: Difference between revisions

Added lock solution
(Created page)
 
(Added lock solution)
Line 3:
==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.
 
Line 21 ⟶ 20:
 
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.
 
{{stub}}
 
==Solutions==
 
There are any number of solutions to race conditions, but most revolve around preventing access to the same data at the same time.
 
===Locks===
 
[[Lock|Locks]] are mechanisms that force one thread to wait until another thread is finished with a piece of data. As an example:
 
CObject* pObj = GetSharedObject();
pObj->Lock();
if ( pObj->Available() )
{
DoSomethingWith( pObj );
}
pObj->Unlock();
 
In the above code, we lock our object before we attempt to do anything with it. Mind you, in this example, we ''don't'' know how Lock() is implemented; Implementations vary between languages, support libraries and operating systems. However, we're assured that no other (appropriately-behaving) thread will be able to make a change to our object while we're working with it. If another thread has a lock when we call Lock(), ''our thread will hang'' until that other thread releases the lock. Once the other thread releases the lock, our thread will continue.
 
{{stub}}