线程竞态工具的使用说明

操作系统环境: 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;
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容