Race conditions
A race condition is another type of concurrency bug that occurs when two or more threads access shared data and try to change it at the same time. This means a situation where the output of a piece of logic requires that interleaved code is run in a particular order -- an order that cannot be guaranteed.
A classic example is of a bank account, where one thread is crediting the account and another is debiting the account. An account operation requires us to retrieve the value, update it, and set it back, which means the ordering of these instructions can interleave with each other.
For example, assume an account starts with $100. Then, we want to credit $50 and debit $100. One possible ordering of the instructions can be something like this:
|
|
|
start value = 100 | ||
get current balance = 100 | ||
get current balance = 100 | ||
set new balance = 100 + 50 | ||
Updated = 150 | ||
set new balance = 100 - 100 | ||
Updated... |