Skip to content
IT glossary
ProgrammingUpdated December 3, 2026

Race condition

Состояние гонки

A bug where the program works correctly only if independent operations happen in a particular order, but nothing guarantees that order.

Also known as: гонка данных, data race

What makes it a race condition?

Start with a rule the program must uphold. If two workers each record one completed job, the total should go up by two, regardless of which worker finishes first. A race condition exists if an order the system permits can break that rule. The fact that tasks sometimes finish in a different order isn't itself a bug.

Example: a lost update

Imagine each worker reads a shared counter, adds one locally, and writes the result back. The counter starts at 10:

Worker A reads 10
Worker B reads 10
Worker A writes 11
Worker B writes 11

Both jobs finished, but the counter says only one did. Each write used the same old value. Making each read and write atomic still allows this sequence. An atomic increment fixes the simple counter because it performs the whole read-modify-write as one operation. If the rule spans several fields, a mutex can protect the entire update, provided all relevant accesses use that same mutex.

Race condition vs. data race

A data race is a narrower memory-model concept. Broadly, it involves conflicting accesses to the same memory location, at least one of them a write, without the ordering required by the language's memory model. The exact definition is language-specific: in C++, for instance, two atomic accesses don't form a data race. The counter example can still lose an update when its reads and writes are atomic, so ruling out data races doesn't prove the program is free of race conditions.

Where else races show up

A single-threaded UI can have a race. A user changes a search query while the first request is still pending. If the old response arrives last and replaces the new results, the screen no longer matches the query. The fix is to check that a response still belongs to the current query before displaying it, not to add a thread lock.

Choose a fix that covers everyone who can change the state. A lock inside one server process won't coordinate other server processes updating the same database row. For a database counter, have the database perform the increment in one statement, such as UPDATE ... SET count = count + 1, rather than reading the value into the application and writing back a computed result.

What interviewers look for

Show one possible sequence of events that breaks the rule, then explain why your fix makes that sequence harmless or impossible. A useful follow-up is to identify exactly what must be atomic: the write alone, the whole update, or a check together with its dependent action. Adding a delay or passing a stress test doesn't establish that all allowed orderings are safe.