Conceptcore
Data race
Also called race on memory, unsynchronized access.
A data race is two accesses to one memory location from different threads, at least one a write, with no synchronization that orders them. In C and C++ it is undefined behaviour.
- Applies to
- core-languages
Idea
Two threads share a variable. Each thread adds 1 to it. After both threads finish, the variable can hold 1, not 2. The second write replaced the first write, so one update is lost.
The memory models of C, C++, Java and Go give this hazard the name data race. Their definitions agree. Two accesses conflict when they use the same memory location and at least one of them is a write.1234 A data race is two conflicting accesses in different threads that no synchronization orders. In C, C++ and Go, a race also needs at least one access that is not atomic.124
The program below forces the bad order. Each thread reads count, then waits at a barrier until the other thread has also read it. Then each thread writes its value plus 1. A barrier makes the order the same on each run, so the output is always 1.
This code runs but gives a wrong answer on purpose.
import threading
count = 0
barrier = threading.Barrier(2)
def add_one():
global count
value = count
barrier.wait()
count = value + 1
workers = [threading.Thread(target=add_one) for _ in range(2)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
print(count)
1
Without the barrier, the program usually prints 2. The wrong order then occurs only sometimes, under load or on another machine. This makes data races hard to find with tests.
A data race and a race condition are different things. A race condition is a bug where the result depends on the order or timing of events. A data race is a fact about memory accesses that a language defines. A program can have a race condition and no data race, when every access is atomic but the logic between the accesses is wrong. A program can also have a data race that by chance gives the correct result.7 The Pitfalls section shows a race condition with no data race. This page is about data races and the tools that find and prevent them. Locks are the topic of Mutual exclusion, and the threads themselves are the topic of Thread.
How it works
The increment has three steps
The statement count += 1 looks like one action. The machine does it in three steps: load the value from memory, add 1, store the result. Another thread can run between any two steps. The Python disassembler shows the three steps for a global variable.
import dis
count = 0
def add_one():
global count
count += 1
for instruction in dis.get_instructions(add_one):
if instruction.opname in ("LOAD_GLOBAL", "BINARY_OP", "STORE_GLOBAL"):
print(instruction.opname, instruction.argrepr)
LOAD_GLOBAL count
BINARY_OP +=
STORE_GLOBAL count
The interpreter can switch threads between these instructions. The Python FAQ gives i = i+1 and D[x] = D[x] + 1 as operations that are not atomic, for this reason.6 The same split occurs in compiled code. The compiler turns count++ into a load, an add and a store, unless the variable is atomic.
Happens-before
The definitions use an order between events called happens-before. Inside one thread, an earlier statement happens before a later one. Between threads, synchronization makes the order. For example, the unlock of a lock happens before a later lock of the same lock. The start and the join of a thread also order events. If neither of two conflicting accesses happens before the other, they race.134 Lamport defined the "happened before" relation for events in a distributed system, and the memory models use the same idea.22
The definition does not mention time. Two accesses one second apart still race when nothing orders them. For this reason a race detector can report a race that did not cause a wrong result in the run.
Sequential consistency for programs with no data race
Each language makes a contract with the programmer. If a program has no data race, it behaves as if the threads take turns in one global order. Each read then sees the last write in that order. This is sequential consistency. The C, C++, Java, Go and JavaScript memory models all give this guarantee to programs with no data race.123413 The Go memory model calls it DRF-SC.4
The contract lets the compiler and the processor reorder memory accesses inside one thread. A reordering is invisible to a program with no data race. A program with a data race can see it. For example, a thread can see a flag set before it sees the data that the flag protects.
What a data race does in each language
The languages differ in what happens when the contract is broken.
| Language | Result of a data race |
|---|---|
| C, C++ | undefined behaviour; the standard puts no limit on the result12 |
| Java | defined but weak; a read can see the value of any racing write, and the program stays type safe3 |
| Go | limited for single words; a race on a multiword value can corrupt memory5 |
| JavaScript, TypeScript | defined for shared memory; racing accesses of the same size do not tear13 |
| C# | the specification lists which reads and writes are atomic; an increment is not among them14 |
| Python | the interpreter stays consistent, but compound updates such as += are not atomic6 |
| Rust | safe code cannot have a data race; the compiler rejects it7 |
In C and C++, "undefined" is meant literally. The standard says that any data race results in undefined behaviour.12 So a compiler can optimize as if no other thread writes a plain variable between two synchronization points. For example, it can load the variable once and reuse the value. The C++ standard also limits the other direction. It forbids most transformations that add a store to a location the program does not write, because that store could add a data race.1
Java must keep the JVM safe even for programs with bugs. The JLS states that "a data race cannot cause incorrect behavior such as returning the wrong length for an array."3 A racing read still sees some value that a thread wrote to that variable. Writes to a long or a double that is not volatile are an exception. The JVM can treat each such write as two 32-bit writes, so a racing read can see half of each.15
The Go memory model gives a middle ground. An implementation can report a data race and stop the program. A racing read of a value no larger than a machine word sees a value that some write stored. A race on an interface, a map, a slice or a string can lead to arbitrary memory corruption.5 The advice in the document is short: "Don't be clever."4
ECMAScript defines data races only for shared memory, which is a SharedArrayBuffer that two agents (for example, a main thread and a worker) can see. Two events are in a race when happens-before does not order them, their memory ranges overlap, and both write or one reads from the other. The race is a data race if either access is not sequentially consistent, or if the ranges only partly overlap.13 The guidelines in the specification say that a racy program can still behave predictably. This holds if no atomic operation takes part in the race and all racing accesses have the same size. Such accesses do not tear, but their order is still not fixed.13
Python has a global interpreter lock (GIL) in its default build. The GIL lets only one thread run Python bytecode at a time, and it switches threads only between bytecode instructions.6 So a single instruction, such as an append to a list, is atomic. The += statement is three instructions, so the GIL does not make it atomic. The FAQ ends its answer with "When in doubt, use a mutex!"6 The free-threaded build has no GIL. Built-in types such as list and dict use internal locks, and the documentation still recommends threading.Lock for shared state.20
How Rust rejects a data race
Safe Rust guarantees that a program has no data race.7 The rules of Ownership and borrowing do most of the work. A value can have many shared references or one mutable reference, never both. Two threads that both write a variable would each need a mutable reference, and the borrow checker allows only one.
This code does not compile, on purpose.
use std::thread;
fn main() {
let mut count = 0;
thread::scope(|s| {
s.spawn(|| count += 1);
s.spawn(|| count += 1);
});
println!("{count}");
}
The compiler stops with error E0499, "cannot borrow count as mutable more than once at a time". The function thread::scope lets threads borrow local variables, because it joins all of its threads before it returns.10
Interior mutability changes a value through a shared reference, so the borrow rules alone do not stop a race. Two marker traits close this gap. A type is Send if a value of it can move to another thread. A type is Sync if threads can share a reference to it, and T is Sync exactly when &T is Send.8 Cell and RefCell are not Sync, and Rc is neither Send nor Sync.8 The function thread::spawn requires its closure and its result to be Send.9 The compiler infers both traits from the fields of a type. The Rust example file shares a Cell<i32> between two threads, and the compiler rejects it with E0277, "Cell<i32> cannot be shared between threads safely".
The Rustonomicon states the limit of this guarantee: "Rust does not prevent general race conditions."7 The check-then-act pitfall below compiles in Rust as well.
Atomic operations
An atomic operation is a read, a write or a read-modify-write that no other thread can see half done. A data race needs at least one access that is not atomic, so atomics remove the race. Each tier 1 language with shared memory has them.
- C has the
_Atomicqualifier and<stdatomic.h>. Postfix++on an atomic object is one read-modify-write with sequentially consistent order.16 - C++ has
std::atomic<T>, Rust hasstd::sync::atomic, and Go hassync/atomic. Rust follows the C++ rules for atomics.19 - Java has
java.util.concurrent.atomic, "a small toolkit of classes that support lock-free thread-safe programming on single variables."17 - C# has the
Interlockedclass.Interlocked.Increment"increments a specified variable and stores the result, as an atomic operation."18 - JavaScript has the
Atomicsobject, which works on typed arrays over aSharedArrayBuffer.13
Each example file shows the fix for its language. Two threads add 1 to an atomic counter 100000 times, and the program prints 200000 on each run.
An atomic variable protects one location. When an update changes two variables together, or reads one and writes another, atomics on each variable are not enough. The program then needs a lock, which Mutual exclusion describes, or it must give each piece of data one owner and pass messages through Channel.
Race detectors
A race detector watches a running program. It records each memory access and each synchronization, and it reports two conflicting accesses that happens-before does not order. ThreadSanitizer (TSan) does this for C and C++. The program is compiled with -fsanitize=thread, and the documentation recommends -O1 and -g as well.12 The report starts with WARNING: ThreadSanitizer: data race and shows the stack of each access.
Go builds the same runtime library into its tool chain.29 The flag -race works with go run, go build and go test. The report starts with WARNING: DATA RACE. By default the program continues after a report and exits with status 66.11 The detector needs cgo, and on systems other than Darwin it also needs a C compiler.11
The C and Go example files use these tools. Each racy program there is a fails block that expects the report of the detector. A racy program never has an output block, because its output is not defined.
A detector finds only races that occur in the run it watches. The Go documentation says that the race detector "only finds races that happen at runtime".11 Code that a test does not reach is not checked. A clean run does not prove that the program has no data race.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Native | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | |
| Go | Standard library | |
| Rust | Native | |
| Kotlin | Standard library | |
| SQL | Does not apply | A query does not touch memory shared between threads; the engine controls concurrent access to rows, and lost updates and write skew are anomalies of transaction isolation. |
| Bash | Does not apply | Background jobs and subshells are separate processes that share no variables. Alternative: Files, pipes and a lock file between processes. |
| PowerShell | Standard library | |
| HTML | Does not apply | Markup has no threads and no shared memory. |
| CSS | Does not apply | Style rules have no threads and no shared memory. |
| Regular expressions | Does not apply | A pattern has no threads and no shared memory. |
The verdict says how the language gives race-free access to shared memory: a language construct (native) or a type in the standard library (stdlib). Each example file shows a counter that two threads increment 100000 times, with an atomic or a lock.
| Language | Verdict | Form |
|---|---|---|
| C | native | _Atomic and <stdatomic.h>; TSan for detection |
| C++ | stdlib | std::atomic<T>; TSan for detection |
| Java | stdlib | java.util.concurrent.atomic; volatile fields |
| Kotlin | stdlib | the JDK atomic classes on the JVM |
| C# | stdlib | System.Threading.Interlocked |
| PowerShell | stdlib | the .NET concurrent collections |
| Go | stdlib | sync/atomic; go run -race for detection |
| Rust | native | Send and Sync checked by the compiler; std::sync::atomic |
| Python | stdlib | threading.Lock; no atomic integer type |
| JavaScript | stdlib | Atomics on a SharedArrayBuffer |
| TypeScript | stdlib | as JavaScript, with types |
| Bash | n/a | background jobs are processes that share no variables |
| SQL | n/a | the engine controls concurrent access to rows |
| Regex | n/a | a pattern has no threads |
| HTML/CSS | n/a | markup and style rules have no threads |
C11 makes threads and atomics optional. An implementation that lacks them defines __STDC_NO_THREADS__ or __STDC_NO_ATOMICS__.31 The C library of the test host has no <threads.h>, so the C examples use POSIX threads.
PowerShell runs each script block of ForEach-Object -Parallel on its own thread. The documentation says that objects passed with $using: must be thread safe, for example the types of System.Collections.Concurrent.21 The PowerShell example file shows a trap: [ref] on an array element refers to a copy, so Interlocked.Increment does not change the array.
import threading
count = 0
lock = threading.Lock()
def work():
global count
for _ in range(100_000):
with lock:
count += 1
workers = [threading.Thread(target=work) for _ in range(2)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
print(count)
200000
- Verdict: stdlib. The
threadingmodule hasLock, andwith lock:holds it for the whole read, add and store ofcount += 1. - The interpreter switches threads only between bytecode instructions, and
count += 1is three of them, so the GIL does not make it atomic. - Python has no atomic integer type in the standard library. Single operations on built-in types, such as
list.append, are atomic, but compound updates are not. - The free-threaded build has no GIL. Its built-in types use internal locks, and the documentation still recommends
threading.Lockfor shared state.
#include <atomic>
#include <print>
#include <thread>
#include <vector>
int main() {
std::atomic<int> count = 0;
{
std::vector<std::jthread> threads;
for (int t = 0; t < 2; t++) {
threads.emplace_back([&count] {
for (int i = 0; i < 100'000; i++) {
count++;
}
});
}
}
std::println("{}", count.load());
}
200000
This code has a memory error, on purpose, and the sanitizer reports it.
#include <thread>
int main() {
int count = 0;
auto work = [&count] {
for (int i = 0; i < 100'000; i++) {
count++;
}
};
std::thread a(work);
std::thread b(work);
a.join();
b.join();
}
- Verdict: stdlib.
std::atomic<int>makescount++one atomic read-modify-write with sequentially consistent order. - A
std::jthreadjoins in its destructor, so the threads finish when the inner block ends, beforecount.load(). - The second program increments a plain
intfrom two threads. Any data race in C++ is undefined behaviour, so it has no output block. ThreadSanitizer reports the race.
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
AtomicInteger count = new AtomicInteger();
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
count.incrementAndGet();
}
};
Thread first = new Thread(work);
Thread second = new Thread(work);
first.start();
second.start();
first.join();
second.join();
System.out.println(count.get());
}
}
200000
- Verdict: stdlib.
AtomicInteger.incrementAndGetis one atomic read-modify-write, so the two threads never lose an update. - A data race in Java does not break type safety. A racing read sees some written value, except that a plain
longordoublecan tear into two 32-bit halves. - A
volatilefield also removes the race on a single read or write. It does not makecount++atomic, because that is still a read and a separate write. Thread.joinorders the writes of each thread before the finalcount.get().
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
static atomic_int count = 0;
static void *work(void *arg) {
(void)arg;
for (int i = 0; i < 100000; i++) {
atomic_fetch_add(&count, 1);
}
return NULL;
}
int main(void) {
pthread_t threads[2];
for (int i = 0; i < 2; i++) {
pthread_create(&threads[i], NULL, work, NULL);
}
for (int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
}
printf("%d\n", atomic_load(&count));
}
200000
This code has a memory error, on purpose, and the sanitizer reports it.
#include <pthread.h>
#include <stdio.h>
static int count = 0;
static void *work(void *arg) {
(void)arg;
for (int i = 0; i < 100000; i++) {
count++;
}
return NULL;
}
int main(void) {
pthread_t threads[2];
for (int i = 0; i < 2; i++) {
pthread_create(&threads[i], NULL, work, NULL);
}
for (int i = 0; i < 2; i++) {
pthread_join(threads[i], NULL);
}
}
- Verdict: native.
_Atomicis a type qualifier of the language, andatomic_intfrom<stdatomic.h>is_Atomic int.atomic_fetch_addis one atomic read-modify-write. - The second program has a plain
static int count. Any data race in C is undefined behaviour, so it has no output block. ThreadSanitizer, enabled with-fsanitize=thread, reportsWARNING: ThreadSanitizer: data race. - C11 makes threads and atomics optional, and an implementation without them defines
__STDC_NO_THREADS__or__STDC_NO_ATOMICS__. The C library of the test host has no<threads.h>, so these programs use POSIX threads.
using System;
using System.Threading;
int count = 0;
var workers = new Thread[2];
for (int t = 0; t < workers.Length; t++)
{
workers[t] = new Thread(() =>
{
for (int i = 0; i < 100_000; i++)
{
Interlocked.Increment(ref count);
}
});
workers[t].Start();
}
foreach (var worker in workers)
{
worker.Join();
}
Console.WriteLine(count);
200000
- Verdict: stdlib.
Interlocked.Incrementincrements the variable and stores the result as one atomic operation. - The C# specification makes reads and writes of
intatomic, but it gives no guarantee for a read-modify-write such ascount++. - Reads and writes of
long,doubleanddecimalneed not be atomic, so a racing read of these types can tear. Interlocked.Incrementwraps on overflow and throws no exception.
const { Worker, isMainThread, workerData } = require("node:worker_threads");
if (isMainThread) {
const shared = new Int32Array(new SharedArrayBuffer(4));
const workers = [1, 2].map(
() => new Worker(__filename, { workerData: shared }),
);
let running = workers.length;
for (const worker of workers) {
worker.on("exit", () => {
running -= 1;
if (running === 0) {
console.log(Atomics.load(shared, 0));
}
});
}
} else {
for (let i = 0; i < 100_000; i++) {
Atomics.add(workerData, 0, 1);
}
}
200000
- Verdict: stdlib. Plain JavaScript values are not shared between threads. A
SharedArrayBufferis the only memory that workers share. Atomics.addon anInt32Arrayover the shared buffer is atomic. A plainshared[0]++in both workers would be a data race.- A data race on shared memory has defined behaviour in ECMAScript. Racing accesses of the same size do not tear, but updates can still be lost.
import { Worker, isMainThread, workerData } from "node:worker_threads";
function finished(worker: Worker): Promise<number> {
return new Promise((resolve) => worker.on("exit", resolve));
}
if (isMainThread) {
const shared = new Int32Array(new SharedArrayBuffer(4));
const workers = [1, 2].map(
() => new Worker(new URL(import.meta.url), { workerData: shared }),
);
await Promise.all(workers.map(finished));
console.log(Atomics.load(shared, 0));
} else {
const shared: Int32Array = workerData;
for (let i = 0; i < 100_000; i++) {
Atomics.add(shared, 0, 1);
}
}
200000
- Verdict: stdlib. TypeScript has the same memory model as JavaScript, and
AtomicsandSharedArrayBufferhave types in the standard library declarations. - The type
Int32ArrayofworkerDatais only a claim to the compiler. The structured clone of the message gives a view of the same shared buffer. - The types do not show which data is shared, so the compiler cannot find a data race.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var count atomic.Int64
var wg sync.WaitGroup
for range 2 {
wg.Add(1)
go func() {
defer wg.Done()
for range 100_000 {
count.Add(1)
}
}()
}
wg.Wait()
fmt.Println(count.Load())
}
200000
This code fails on purpose. The output below is the error.
package main
import "sync"
func main() {
count := 0
var wg sync.WaitGroup
for range 2 {
wg.Add(1)
go func() {
defer wg.Done()
for range 1000 {
count++
}
}()
}
wg.Wait()
}
- Verdict: stdlib.
sync/atomicgives the typeatomic.Int64, whoseAddis one atomic read-modify-write. - The second program has a plain
count++in two goroutines.go run -racereportsWARNING: DATA RACEand the program exits with status 66, the default exit code of the detector. - The race detector needs cgo. On systems other than Darwin, it also needs a C compiler.
- A race on a single word gives some written value. A race on an interface, map, slice or string can corrupt memory.
use std::sync::atomic::{AtomicU32, Ordering};
use std::thread;
fn main() {
let count = AtomicU32::new(0);
thread::scope(|s| {
for _ in 0..2 {
s.spawn(|| {
for _ in 0..100_000 {
count.fetch_add(1, Ordering::Relaxed);
}
});
}
});
println!("{}", count.into_inner());
}
200000
This code does not compile, on purpose.
use std::cell::Cell;
use std::thread;
fn main() {
let count = Cell::new(0);
thread::scope(|s| {
s.spawn(|| count.set(count.get() + 1));
s.spawn(|| count.set(count.get() + 1));
});
println!("{}", count.get());
}
- Verdict: native. The compiler checks
SendandSync, so safe code cannot share aCellbetween threads. The second program fails with E0277, "Cell<i32>cannot be shared between threads safely". AtomicU32isSync, so both threads can hold a shared reference to it.fetch_addwithOrdering::Relaxedis atomic, and the end ofthread::scopejoins the threads beforeinto_inner.thread::scopelets the threads borrow the local variable, because it joins every thread before it returns.- The check does not cover
unsafecode, and it does not prevent race conditions.
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread
fun main() {
val count = AtomicInteger()
val workers = List(2) {
thread {
repeat(100_000) { count.incrementAndGet() }
}
}
workers.forEach { it.join() }
println(count.get())
}
200000
- Verdict: stdlib. On the JVM, Kotlin uses the JDK class
java.util.concurrent.atomic.AtomicInteger, so the rules of the Java memory model apply. kotlin.concurrent.threadcreates and starts a JVM thread.joinorders the work of each thread before the final read.- A plain
var countwithcount++in both threads has a data race and can lose updates, as in Java. The Kotlin compiler does not report it.
$counts = [System.Collections.Concurrent.ConcurrentDictionary[string, int]]::new()
1..2 | ForEach-Object -ThrottleLimit 2 -Parallel {
$shared = $using:counts
$addOne = [Func[string, int, int]] { param($key, $value) $value + 1 }
for ($i = 0; $i -lt 10000; $i++) {
[void]$shared.AddOrUpdate('total', 1, $addOne)
}
}
Write-Output $counts['total']
20000
This code runs but gives a wrong answer on purpose.
$box = [int[]]::new(1)
1..2 | ForEach-Object -ThrottleLimit 2 -Parallel {
$shared = $using:box
for ($i = 0; $i -lt 10000; $i++) {
[void][System.Threading.Interlocked]::Increment([ref]$shared[0])
}
}
Write-Output $box[0]
0
- Verdict: stdlib.
ForEach-Object -Parallelruns script blocks on separate threads. When the blocks change shared state, the documentation asks for thread-safe objects, such as theSystem.Collections.Concurrenttypes. ConcurrentDictionarylocks its writes.AddOrUpdatecalls the update delegate outside the lock and can call it more than once, so the delegate must have no side effects. Here it only returns$value + 1.- The second program passes
[ref]$shared[0]toInterlocked.Increment. PowerShell makes a reference to a copy of the element, so the array keeps 0. This is a bug of the program, not a data race.
Variations and related ideas
- Race condition. A bug where the result depends on the order of events. It can occur with no data race and with one thread (see Pitfalls). Netzer and Miller call this a general race.24
- Benign data race. A race that the programmer believes is harmless, such as a statistics counter that may lose updates. C and C++ have no such category, because every data race is undefined behaviour.1
- Torn read or write. A read that sees part of one write and part of another. Java allows it for plain
longanddouble.15 Go allows memory corruption for multiword values.5 C# guarantees atomic access only for the types listed in its specification.14 - Memory ordering. Atomics in C, C++ and Rust take an order argument.
memory_order::relaxedmakes the access atomic but orders no other memory.3219 The Rust example usesOrdering::Relaxed, because only the final total matters and the join of the threads orders the read. - Lock-free data structures. Structures built from compare-and-swap and other atomics instead of locks. They have no data race, but they can still have race conditions.
- Single-threaded concurrency. Code in an event loop has no data race, because only one task runs at a time. It can still have race conditions at each
await(see Async/await).
Pitfalls
Check then act with atomic operations
Each access below is atomic, so the program has no data race. It still has a race condition. Two threads each check the balance and then withdraw 80. The barrier puts both checks before both withdrawals, so the balance goes below zero.
This code runs but gives a wrong answer on purpose.
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static final AtomicInteger balance = new AtomicInteger(100);
static final CyclicBarrier bothChecked = new CyclicBarrier(2);
static void withdraw() {
try {
if (balance.get() >= 80) {
bothChecked.await();
balance.addAndGet(-80);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws InterruptedException {
Thread first = new Thread(Main::withdraw);
Thread second = new Thread(Main::withdraw);
first.start();
second.start();
first.join();
second.join();
System.out.println(balance.get());
}
}
-60
The check and the action must be one atomic step. A compare-and-set loop does this. compareAndSet(current, current - 80) changes the balance only if it still holds the value that the thread checked. If it fails, the thread reads again and checks again.17 In the fixed program, both threads still pass the barrier after their first check. One compareAndSet succeeds. The other fails, reads 20 and stops.
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static final AtomicInteger balance = new AtomicInteger(100);
static final CyclicBarrier bothChecked = new CyclicBarrier(2);
static void withdraw() {
try {
boolean waited = false;
while (true) {
int current = balance.get();
if (current < 80) {
return;
}
if (!waited) {
bothChecked.await();
waited = true;
}
if (balance.compareAndSet(current, current - 80)) {
return;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws InterruptedException {
Thread first = new Thread(Main::withdraw);
Thread second = new Thread(Main::withdraw);
first.start();
second.start();
first.join();
second.join();
System.out.println(balance.get());
}
}
20
A lock around the check and the action also works, and it is the usual fix when the step touches more than one variable.
A race condition with one thread
JavaScript runs this code on one thread, so it has no data race. Each await lets other tasks run, so the check and the action can still interleave. Both calls check the balance, then both wait, then both subtract.
This code runs but gives a wrong answer on purpose.
let balance = 100;
function audit() {
return new Promise((resolve) => setTimeout(resolve, 10));
}
async function withdraw(amount) {
if (balance >= amount) {
await audit();
balance -= amount;
}
}
async function main() {
await Promise.all([withdraw(80), withdraw(80)]);
console.log(balance);
}
main();
-60
The fix puts the check and the change in the same synchronous part of the function, before the await. No other task can run between them.
let balance = 100;
function audit() {
return new Promise((resolve) => setTimeout(resolve, 10));
}
async function withdraw(amount) {
if (balance < amount) {
return false;
}
balance -= amount;
await audit();
return true;
}
async function main() {
const results = await Promise.all([withdraw(80), withdraw(80)]);
console.log(results, balance);
}
main();
[ true, false ] 20
Async/await describes where an async function can pause.
A plain flag between threads
A thread often sets a flag to tell another thread that data is ready. With a plain bool, the write and the read of the flag race, and so do the accesses to the data. The C++ standard makes the program undefined.1 A compiler can read the flag once and loop forever, or the reader can see the flag before the data. Here ThreadSanitizer reports the race. The call to yield in the loop keeps this build from hanging, but it does not make the program correct.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <thread>
int main() {
int data = 0;
bool ready = false;
std::thread producer([&] {
data = 42;
ready = true;
});
while (!ready) {
std::this_thread::yield();
}
int seen = data;
producer.join();
return seen == 42 ? 0 : 1;
}
The fix makes the flag atomic. A store to a std::atomic<bool> and a load that sees it synchronize, so the write of data happens before the read of data.1
#include <atomic>
#include <print>
#include <thread>
int main() {
int data = 0;
std::atomic<bool> ready = false;
std::thread producer([&] {
data = 42;
ready = true;
});
while (!ready) {
std::this_thread::yield();
}
std::println("{}", data);
producer.join();
}
42
In Java, a volatile field gives the same effect.3
A passing test proves nothing
A racy program usually gives the correct result. The bad interleaving needs exact timing, which a test machine may never produce. A race detector helps, but it sees only the code paths that the run executes.11 Run the tests with the detector on, and keep shared mutable state small, so that a reader can check each access.
Cost
- Atomic operations. This page does not measure the cost of atomics. A relaxed order asks only for atomicity and orders no other memory, so it places the fewest limits on the compiler and the processor.32
- ThreadSanitizer. The Clang documentation gives a typical slowdown of 5x to 15x and a memory overhead of 5x to 10x.12 It does not support static linking of
libcorlibstdc++.12 - The Go race detector. The Go documentation gives a memory use of 5 to 10 times that of the normal program. The execution time is 2 to 20 times longer.11
- Rust. The
SendandSyncchecks run in the compiler and add nothing to the running program.8
History
- 1978. Leslie Lamport defined the "happened before" relation on the events of a distributed system.22
- 1990. Sarita Adve and Mark Hill defined weak ordering as a contract: hardware appears sequentially consistent to a program that obeys a synchronization model.23
- 1992. Robert Netzer and Barton Miller separated general races from data races.24
- 1997. Stefan Savage and others described Eraser, a dynamic detector that checks that each shared variable is protected by a consistent set of locks.25
- 2005. Jeremy Manson, William Pugh and Sarita Adve published the revised Java memory model. It gives a guarantee to programs with no data race and limits to programs with one.26
- 2008. Hans Boehm and Sarita Adve described the C++ memory model, where a data race gives undefined semantics.27
- 2009. Konstantin Serebryany and Timur Iskhodzhanov described ThreadSanitizer.28
- 2012 and 2013. The ThreadSanitizer runtime was integrated with Go, and the Go blog introduced the race detector in June 2013.29
- 2015. The Rust blog post "Fearless Concurrency with Rust" stated that the compiler prevents all data races in safe code.30
References
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [intro.races], paragraph 2 (conflict), paragraph 21 and note 21 (data race, undefined behaviour, sequential consistency), paragraph 23 note 22 and paragraph 24 note 23 (compiler transformations)
- N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 5.1.2.4 Multi-threaded executions and data races, paragraphs 4, 25 and 26 (NOTE 12)
- The Java Language Specification, Java SE 25 Edition, 17.4.1 Shared Variables; 17.4.3 Programs and Program Order; 17.4.5 Happens-before Order
- The Go Memory Model, Overview (definition of a data race, DRF-SC); Advice
- The Go Memory Model, Implementation Restrictions for Programs Containing Data Races
- Python Library and Extension FAQ, Python 3.14, What kinds of global value mutation are thread-safe?
- The Rustonomicon, Data Races and Race Conditions
- The Rustonomicon, Send and Sync
- Rust standard library, std::thread::spawn, the bounds F, Send and 'static, and their explanation
- Rust standard library, std::thread::scope, the description (borrowing non-'static data; automatic join)
- Data Race Detector, Go documentation, How To Use; Report Format; Options; Requirements; Runtime Overheads
- Clang documentation, ThreadSanitizer, Introduction; Usage; Limitations
- ECMA-262, ECMAScript 2026 Language Specification, 29.8 Races; 29.9 Data Races; 29.10 Data Race Freedom; 29.11 Shared Memory Guidelines, Note 1
- C# language specification, Variables, 9.6 Atomicity of variable references
- The Java Language Specification, Java SE 25 Edition, 17.7 Non-Atomic Treatment of double and long
- N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.5.2.4 Postfix increment and decrement operators, paragraph 2; 7.17.7.5 The atomic_fetch and modify generic functions
- Java SE 25 API, Package java.util.concurrent.atomic, Description (first sentence; compareAndSet as a read-modify-write operation)
- .NET API reference, Interlocked.Increment Method, Definition; Increment(Int32), Remarks
- Rust standard library, Module std::sync::atomic, the module description; Memory model for atomic accesses
- Python HOWTO, Python support for free threading, Python 3.14, Thread safety
- PowerShell reference, ForEach-Object, Example 14 (thread safe variable references); Notes, the Important box on the Using scope modifier
- Leslie Lamport, Time, clocks, and the ordering of events in a distributed system, Communications of the ACM 21(7), 1978, the definition of the "happened before" relation
- Sarita V. Adve and Mark D. Hill, Weak ordering, a new definition, ISCA 1990, the definition of weak ordering with respect to a synchronization model
- Robert H. B. Netzer and Barton P. Miller, What are race conditions? Some issues and formalizations, ACM Letters on Programming Languages and Systems 1(1), 1992, the distinction between general races and data races
- Stefan Savage, Michael Burrows, Greg Nelson, Patrick Sobalvarro and Thomas Anderson, Eraser, a dynamic data race detector for multithreaded programs, ACM Transactions on Computer Systems 15(4), 1997, the lockset algorithm
- Jeremy Manson, William Pugh and Sarita V. Adve, The Java memory model, POPL 2005, the guarantee for correctly synchronized programs and the semantics of programs with data races
- Hans-J. Boehm and Sarita V. Adve, Foundations of the C++ concurrency memory model, PLDI 2008, the model where a data race gives undefined semantics
- Konstantin Serebryany and Timur Iskhodzhanov, ThreadSanitizer, data race detection in practice, WBIA 2009, the description of the detector
- Dmitry Vyukov and Andrew Gerrand, Introducing the Go Race Detector, The Go Blog, 26 June 2013, the introduction (based on the ThreadSanitizer runtime library, integrated with Go in September 2012)
- Aaron Turon, Fearless Concurrency with Rust, Rust Blog, 10 April 2015, the introduction and the section on Send
- N1570, Committee Draft of ISO/IEC 9899:2011 (C11), 6.10.8.3 Conditional feature macros (__STDC_NO_ATOMICS__, __STDC_NO_THREADS__)
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [atomics.order], paragraph 1.1 and note 2 (memory_order::relaxed), paragraph 10 (read-modify-write operations)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag TQ2SVE Edit this page History Report an error Markdown