ThreadSanitizer(又稱為TSan)是一個用于C/C++的數據競爭檢測器。在并發系統中,數據競爭是最常見且最難調試的錯誤類型之一。當兩個線程并發訪問同一個變量,并且至少有一個訪問是寫操作時,就會發生數據競爭。C++11標準正式將數據競爭定義為未定義行為。
$ cat simple_race.cc
#include <pthread.h>
#include <stdio.h>int Global;void *Thread1(void *x) {Global++;return NULL;
}void *Thread2(void *x) {Global--;return NULL;
}int main() {pthread_t t[2];pthread_create(&t[0], NULL, Thread1, NULL);pthread_create(&t[1], NULL, Thread2, NULL);pthread_join(t[0], NULL);pthread_join(t[1], NULL);
}
g++ -fsanitize=thread -g k.cc
更多例子見https://github.com/google/sanitizers/wiki/ThreadSanitizerPopularDataRaces