race condition race condition in a logic circuit here t1 and t2 represent the propagation delays of the logic elements when the input value a changes from low to high the circuit outputs a short spike of duration t1 t2 t2 t1 a race condition or race hazard is the behavior of an electronics software or other system where the output is dependent on the sequence or timing of other uncontrollable events it becomes a bug when events do not happen in the order the programmer intended the term race condition was already in use by 1954 for example in da huffmans doctoral thesis the synthesis of sequential switching circuits race conditions can occur especially in logic circuits multithreaded or distributed software programs electronics a typical example of a race condition may occur when a logic gate combines signals that have traveled along different paths from the same source the inputs to the gate can change at slightly different times in response to a change in the source signal the output may for a brief period change to an unwanted state before settling back to the designed state certain systems can tolerate such glitches but if this output functions as a clock signal for further systems that contain memory for example the system can rapidly depart from its designed behaviour in effect the temporary glitch becomes a permanent glitch consider for example a twoinput and gate fed with a logic signal a on one input and its negation not a on another input in theory the output a and not a should never be true if however changes in the value of a take longer to propagate to the second input than the first when a changes from false to true then a brief period will ensue during which both inputs are true and so the gates output will also be true design techniques such as karnaugh maps encourage designers to recognize and eliminate race conditions before they cause problems often logic redundancy can be added to eliminate some kinds of races as well as these problems some logic elements can enter metastable states which create further problems for circuit designers critical and noncritical forms a critical race condition occurs when the order in which internal variables are changed determines the eventual state that the state machine will end up in a noncritical race condition occurs when the order in which internal variables are changed does not determine the eventual state that the state machine will end up in static dynamic and essential forms a static race condition occurs when a signal and its complement are combined together a dynamic race condition occurs when it results in multiple transitions when only one is intended they are due to interaction between gates it can be eliminated by using no more than two levels of gating an essential race condition occurs when an input has two transitions in less than the total feedback propagation time sometimes they are cured using inductive delay line elements to effectively increase the time duration of an input signal software race conditions arise in software when an application depends on the sequence or timing of processes or threads for it to operate properly as with electronics there are critical race conditions that result in invalid execution and bugs critical race conditions often happen when the processes or threads depend on some shared state operations upon shared states are critical sections that must be mutually exclusive failure to obey this rule opens up the possibility of corrupting the shared state the memory model defined in the c11 and c11 standards uses the term data race for a race condition caused by potentially concurrent operations on a shared memory location of which at least one is a write a c or c program containing a data race has undefined behavior race conditions have a reputation of being difficult to reproduce and debug since the end result is nondeterministic and depends on the relative timing between interfering threads problems occurring in production systems can therefore disappear when running in debug mode when additional logging is added or when attaching a debugger often referred to as a heisenbug it is therefore better to avoid race conditions by careful software design rather than attempting to fix them afterwards example as a simple example let us assume that two threads want to increment the value of a global integer variable by one ideally the following sequence of operations would take place thread 1 thread 2 integer value 0 read value 0 increase value 0 write back 1 read value 1 increase value 1 write back 2 in the case shown above the final value is 2 as expected however if the two threads run simultaneously without locking or synchronization the outcome of the operation could be wrong the alternative sequence of operations below demonstrates this scenario thread 1 thread 2 integer value 0 read value 0 read value 0 increase value 0 increase value 0 write back 1 write back 1 in this case the final value is 1 instead of the expected result of 2 this occurs because here the increment operations are not mutually exclusive mutually exclusive operations are those that cannot be interrupted while accessing some resource such as a memory location computer security many software race conditions have associated computer security implications a race condition allows an attacker with access to a shared resource to cause other actors that utilize that resource to malfunction resulting in effects including denial of service a specific kind of race condition involves checking for a predicate eg for authentication then acting on the predicate while the state can change between the time of check and the time of use when this kind of bug exists in securitysensitive code a security vulnerability called a timeofchecktotimeofuse tocttou bug is created race conditions are also intentionally used to create hardware random number generators and physically unclonable functions pufs can be created by designing circuit topologies with identical paths to a node and relying on manufacturing variations to randomly determine which paths will complete first by measuring each manufactured circuits specific set of race condition outcomes a profile can be collected for each circuit and kept secret in order to later verify a circuits identity file systems two or more programs may collide in their attempts to modify or access a file system which can result in data corruption or privilege escalation file locking provides a commonly used solution a more cumbersome remedy involves organizing the system in such a way that one unique process running a daemon or the like has exclusive access to the file and all other processes that need to access the data in that file do so only via interprocess communication with that one process this requires synchronization at the process level a different form of race condition exists in file systems where unrelated programs may affect each other by suddenly using up available resources such as disk space memory space or processor cycles software not carefully designed to anticipate and handle this race situation may then become unpredictable such a risk may be overlooked for a long time in a system that seems very reliable but eventually enough data may accumulate or enough other software may be added to critically destabilize many parts of a system an example of this occurred with the near loss of the mars rover spirit not long after landing a solution is for software to request and reserve all the resources it will need before beginning a task if this request fails then the task is postponed avoiding the many points where failure could have occurred alternatively each of those points can be equipped with error handling or the success of the entire task can be verified afterwards before continuing a more common approach is to simply verify that enough system resources are available before starting a task however this may not be adequate because in complex systems the actions of other running programs can be unpredictable networking in networking consider a distributed chat network like irc where a user who starts a channel automatically acquires channeloperator privileges if two users on different servers on different ends of the same network try to start the samenamed channel at the same time each users respective server will grant channeloperator privileges to each user since neither server will yet have received the other servers signal that it has allocated that channel this problem has been largely solved by various irc server implementations in this case of a race condition the concept of the shared resource covers the state of the network what channels exist as well as what users started them and therefore have what privileges which each server can freely change as long as it signals the other servers on the network about the changes so that they can update their conception of the state of the network however the latency across the network makes possible the kind of race condition described in this case heading off race conditions by imposing a form of control over access to the shared resourcesay appointing one server to control who holds what privilegeswould mean turning the distributed network into a centralized one at least for that one part of the network operation race conditions can also exist when a computer program is written with nonblocking sockets in which case the performance of the program can be dependent on the speed of the network link lifecritical systems software flaws in lifecritical systems can be disastrous race conditions were among the flaws in the therac25 radiation therapy machine which led to the death of at least three patients and injuries to several more another example is the energy management system provided by ge energy and used by ohiobased firstenergy corp among other power facilities a race condition existed in the alarm subsystem when three sagging power lines were tripped simultaneously the condition prevented alerts from being raised to the monitoring technicians delaying their awareness of the problem this software flaw eventually led to the north american blackout of 2003 ge energy later developed a software patch to correct the previously undiscovered error examples outside of computing biology this section needs expansion you can help by adding to it october 2016 neuroscience is demonstrating that race conditions can occur in mammal rat brains as well tools many software tools exist to help detect race conditions in software they can be largely categorized into two groups static analysis tools and dynamic analysis tools thread safety analysis is a static analysis tool for annotationbased intraprocedural static analysis originally implemented as a branch of gcc and now reimplemented in clang supporting pthreads dynamic analysis tools include intel inspector a memory and thread checking and debugging tool to increase the reliability security and accuracy of cc and fortran applications intel advisor a sampling based simd vectorization optimization and shared memory threading assistance tool for c c c and fortran software developers and architects threadsanitizer which uses binary valgrindbased or source llvmbased instrumentation and supports pthreads software testing portal call collision concurrency control deadlock hazard logic nearduplicate article linearizability racetrack problem synchronization computer science time of check to time of use karam gm buhr rja august 1990 starvation and critical race analyzers for ada ieee transactions on software engineering 16 8 829843 doi1011093257622 fuhrer rm lin b nowick sm march 1995 algorithms for the optimal state assignment of asynchronous state machines advanced research in vlsi 1995 proceedings 16th conference on pp5975 doi101109arvlsi1995515611 isbn0818670479 as pdf paper a novel framework for solving the state assignment problem for eventbased specifications by luciano lavagno cho w moon robert k brayton and alberto sangiovannivincentelli wheeler david a 7 october 2004 secure programmer prevent race conditionsresource contention can be used against you pdf ibm developerworks archived from the original pdf on nov 14 2013 chapter avoid race conditions secure programming for linux and unix howto race conditions security and immutability in java with sample source code and comparison to c code by chiral software karpov andrey 11 april 2009 interview with dmitriy vyukov the author of relacy race detector rrd intel software library articles microsoft support description vteconcurrent computinggeneral concurrency concurrency control process calculi csp ccs acp lotos calculus ambient calculus apicalculus pepa joincalculus classic problems aba problem cigarette smokers problem deadlock dining philosophers problem producerconsumer problem race condition readerswriters problem sleeping barber problem category concurrent computing 