美文网首页
线程竞态工具的使用说明

线程竞态工具的使用说明

作者: followhy | 来源:发表于2014-08-24 18:29 被阅读59次

操作系统环境: ubuntu12.04

step 1 安装Clang,必须是3.3以上的版本

sudo apt-get install clang-3.3

step 2 编写测试程序

#include <pthread.h>  

int global;  
    
void * tfun1(void *x)   
{  
    global = 1;  
    return x;  
}  

int main()  
{
    pthread_t t;  
    pthread_create(&t, NULL, tfun1, NULL);  
    global = 2;  
    pthread_join(t, NULL);  
    return global;  
}

step 3 编译程序

clang -fsanitize=thread -g -O1 test.c

step 4 察看运行结果

./a.out
==================
WARNING: ThreadSanitizer: data race (pid=13047)  
Write of size 4 at 0x7fbe3dc16730 by thread T1:  
 #0 tfun1 /home/songwenbin/Play/testscanitizer/test.c:7 (exe+0x000000055260)  

Previous write of size 4 at 0x7fbe3dc16730 by main thread:  
#0 main /home/songwenbin/Play/testscanitizer/test.c:15 (exe+0x0000000552b4)  

Thread T1 (tid=13049, running) created by main thread at:  
#0 pthread_create ??:0 (exe+0x0000000266c2)  
#1 main /home/songwenbin/Play/testscanitizer/test.c:14 (exe+0x0000000552a4)    
SUMMARY: ThreadSanitizer: data race /home/songwenbin/Play/testscanitizer/test.c:7 > tfun1
==================

可以看出由于main和tfun1函数都修改global全局变量,两个函数的代码都没有对global全局变量的使用做保护,所以thread-sanitizer给出了警告提示

step 5 对共享变量加入保护代码

#include <pthread.h>

int global;
pthread_mutex_t mutex;
    
void * tfun1(void *x) 
{
    pthread_mutex_lock(&mutex);
    global = 1;
    pthread_mutex_unlock(&mutex);
    return x;
}

int main()
{
    pthread_mutex_init(&mutex, NULL);  
    pthread_t t;  
    pthread_create(&t, NULL, tfun1, NULL);  

    pthread_mutex_lock(&mutex);
    global = 2;
    pthread_mutex_unlock(&mutex);
 
    pthread_join(t, NULL);
    return global;
}

再编译运行此代码则不会出现警告信息

相关文章

  • WWDC 2016 Thread Santizer and St

    一. Thread Santizer(TSAN) 线程竞态检测工具:可以在运行时发现线程竞态 竞态 两个线程同时访...

  • 线程竞态工具的使用说明

    操作系统环境: ubuntu12.04 step 1 安装Clang,必须是3.3以上的版本 step 2 编写...

  • go 竞态检测

    Go 工具套件在 Go 版本 1.1 引入了一个竞态检测工具(race detector)。这个竞态检测工具是在编...

  • 竟态条件 racing condition

    多个线程读时,线程是安全的。当两个线程竞争同一资源时,如果对资源的访问顺序敏感,就称存在竞态条件。我的理解,竞态条...

  • 线程安全与资源共享

    允许被多个线程同时执行的代码称作线程安全的代码。线程安全的代码不包含竞态条件。当多个线程同时更新共享资源时会引发竞...

  • java并发的资源

    允许被多个线程同时执行的代码称作线程安全的代码。线程安全的代码不包含竞态条件。当多个线程同时更新共享资源时会引发竞...

  • Java并发

    无状态对象一定是线程安全的 竞态条件当某个计算的正确性取决于多个线程的交替执行时序时,那么久会发生竞态条件。换句话...

  • 竞态 synchronized关键字

    多线程编程中对于同样的输入,结果时而正确时而错误的现象称为竞态。正确性与时间相关。竞态的两种模式read-modi...

  • 竞态条件和临界区

    当两个线程竞争同一资源时,如果对资源的访问顺序敏感,就称存在竞态条件。导致竞态条件发生的代码区称作临界区。

  • 并发编程-基础知识

    什么是线程安全 无状态对象一定是线程安全的 原子性 竞态条件(Race Condition):不恰当的执行时序导致...

网友评论

      本文标题:线程竞态工具的使用说明

      本文链接:https://www.haomeiwen.com/subject/fvadtttx.html