操作系統(tǒng)環(huán)境: 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 察看運行結(jié)果
./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函數(shù)都修改global全局變量绞绒,兩個函數(shù)的代碼都沒有對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;
}
再編譯運行此代碼則不會出現(xiàn)警告信息