thread sanitizer初体验

  |   0 评论   |   0 浏览

背景

ThreadSanitizer是一个数据竞争检查工具,又叫TSan。数据竞争发生在两个线程同时访问同一个变量时,而其中一个线程又有写操作时。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++ simple_race.cc -fsanitize=thread -fPIE -pie -g

运行

==================
WARNING: ThreadSanitizer: data race (pid=2388600)
  Read of size 4 at 0x557472b6501c by thread T2:
    #0 Thread2(void*) /home/abeffect/cppProjects/asan/simple_race.cc:12 (a.out+0x12e9)

  Previous write of size 4 at 0x557472b6501c by thread T1:
    #0 Thread1(void*) /home/abeffect/cppProjects/asan/simple_race.cc:7 (a.out+0x12a6)

  Location is global 'Global' of size 4 at 0x557472b6501c (a.out+0x00000000401c)

  Thread T2 (tid=2388603, running) created by main thread at:
    #0 pthread_create ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:962 (libtsan.so.0+0x5ea79)
    #1 main /home/abeffect/cppProjects/asan/simple_race.cc:19 (a.out+0x137e)

  Thread T1 (tid=2388602, finished) created by main thread at:
    #0 pthread_create ../../../../src/libsanitizer/tsan/tsan_interceptors_posix.cpp:962 (libtsan.so.0+0x5ea79)
    #1 main /home/abeffect/cppProjects/asan/simple_race.cc:18 (a.out+0x135d)

SUMMARY: ThreadSanitizer: data race /home/abeffect/cppProjects/asan/simple_race.cc:12 in Thread2(void*)
==================
ThreadSanitizer: reported 1 warnings

参考

  1. ThreadSanitizerCppManual@github