返回介绍

利用 Thread Sanitizer 工具检查数据竞争的问题

发布于 2025-02-22 23:07:55 字数 1517 浏览 0 评论 0 收藏 0

例子

#include <pthread.h>
int Global;
void *Thread1(void *x) {
  Global = 42;
  return x;
}
int main(void) {
  pthread_t t;
  pthread_create(&t, NULL, Thread1, NULL);
  Global = 43;
  pthread_join(t, NULL);
  return Global;
}

技巧

gcc 从 4.8 版本起,集成了 Address Sanitizer 工具,可以用来检查数据竞争的问题(编译时指定“ -fsanitize=thread -fPIE -pie ”)。以上面程序为例:

gcc -fsanitize=thread -fPIE -pie -g -o a a.c -lpthread

执行 a 程序:

[root@localhost nan]# ./a
==================
WARNING: ThreadSanitizer: data race (pid=14545)
  Write of size 4 at 0x7f055b4802b0 by thread T1:
    #0 Thread1 /home/nan/a.c:4 (a+0x000000000a87)

  Previous write of size 4 at 0x7f055b4802b0 by main thread:
    #0 main /home/nan/a.c:10 (a+0x000000000ae8)

  Location is global 'Global' of size 4 at 0x7f055b4802b0 (a+0x0000002012b0)

  Thread T1 (tid=14547, running) created by main thread at:
    #0 pthread_create /opt/gcc-4.9.2/src/gcc-4.9.2/libsanitizer/tsan/tsan_interceptors.cc:877 (libtsan.so.0+0x00000004aa83)
    #1 main /home/nan/a.c:9 (a+0x000000000ad9)

SUMMARY: ThreadSanitizer: data race /home/nan/a.c:4 Thread1
==================
ThreadSanitizer: reported 1 warnings

可以看到,执行程序时检测出了对 Global 变量的竞争访问。
详情参见 gcc 手册

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文