data-race

A thread writes a variable another thread can use at the same time, with no lock both hold.

Group
Code
Runs
On by default
Level
warning
Reads
Every file
Fix
None: which lock should guard the variable, or whether it should be atomic, is a design choice

Why

A function started as a thread, as with pthread_create, threading.Thread, Thread.new, or new Thread, writes a variable or a field that another thread can read or write at the same time: another thread running the same function, a different thread, or the function that started the thread before it joins it. No lock is held by both, so the two accesses can interleave and the program can read a torn or stale value or lose an update. Take one lock around every access to the variable, as with a mutex, with lock:, synchronize, or synchronized, or make it atomic. In Python and Ruby, whose global locks run each read and write whole, only an update such as x += 1 races. Ur reads locks by the expression that names them and does not follow pointers, so each finding lists the assumption it relied on.

The fix, as Ur suggests it: take one mutex around every access, or make the variable atomic.

For agents

Guard every access to a variable that threads share with one mutex, or make the variable atomic.

Example

src/counter.c
#include <pthread.h>

static long hits = 0;

static void *count(void *arg) {
    for (int i = 0; i < 1000; i++) {
        hits++;
    }
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, count, NULL);
    pthread_create(&b, NULL, count, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    return hits == 2000 ? 0 : 1;
}
What Ur prints
$ ur lint --rule data-race
warning[data-race]: `hits` is written by the thread running `count`, with no lock held, and more than one such thread runs at once
  --> ./src/counter.c:7:9 function `count`
  = step 1: ./src/counter.c:14:5 a thread running `count` starts here
  = step 2: ./src/counter.c:15:5 a thread running `count` starts here
  = assumes: locks-by-name
  = hint: take one mutex around every access, or make the variable atomic
  = see: Eraser: A Dynamic Data Race Detector for Multithreaded Programs, Stefan Savage, Michael Burrows, Greg Nelson, Patrick Sobalvarro, and Thomas Anderson, ACM Transactions on Computer Systems 15(4) (1997-11-01), https://doi.org/10.1145/265924.265927
0 clone classes and 1 concurrency finding in 1 file

Try it in the playground →

Source

Eraser: A Dynamic Data Race Detector for Multithreaded Programs, Stefan Savage, Michael Burrows, Greg Nelson, Patrick Sobalvarro, and Thomas Anderson, ACM Transactions on Computer Systems 15(4) (1997-11-01).