Skip to content
systemcoding.dev
Concurrency

Build and run tests with -fsanitize=thread

Compile with -fsanitize=thread -g and run your tests to get a ThreadSanitizer report for every unsynchronised access, using GCC 14 or Clang 19.

2 min read
Summarize in AI

ThreadSanitizer instruments memory accesses and reports two threads touching the same address without ordering. You get it by adding one flag to compile and link. GCC 14 on x86-64 Linux; Clang 19 takes the same flags.

race.cc
#include <pthread.h>
#include <stdio.h>

int counter;

void *work(void *arg) {
    for (int i = 0; i < 1000; i++) counter++;
    return arg;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, work, NULL);
    pthread_create(&b, NULL, work, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("%d\n", counter);
}
Shell
gcc-14 -fsanitize=thread -g -O1 race.c -o race -pthread
./race

The report looks like this, with addresses, thread ids and line numbers that will differ:

Text
WARNING: ThreadSanitizer: data race (pid=4121)
  Write of size 4 at 0x000000c0a1c0 by thread T2:
    #0 work race.c:7 (race+0x1234)

  Previous write of size 4 at 0x000000c0a1c0 by thread T1:
    #0 work race.c:7 (race+0x1234)

SUMMARY: ThreadSanitizer: data race race.c:7 in work

Keep -g so the frames carry file and line, and -O1 or -O2 so the run stays quick; -O0 works but is slow. The tool only sees races on the paths your run executes, so a clean run proves nothing about code the test never reached. It also needs the whole program built with the flag, including libraries you want checked, and it cannot be combined with -fsanitize=address in one binary. The process exits with status 66 when it reported a race. See the ThreadSanitizer manual.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.