1 // RUN: %clang_tsan -O1 %s -o %t && %deflake %run %t | FileCheck %s 2 #include <pthread.h> 3 #include <stdio.h> 4 #include <stddef.h> 5 #include <unistd.h> 6 7 pthread_mutex_t Mtx; 8 int Global; 9 10 void *Thread1(void *x) { 11 pthread_mutex_init(&Mtx, 0); 12 pthread_mutex_lock(&Mtx); 13 Global = 42; 14 pthread_mutex_unlock(&Mtx); 15 return NULL; 16 } 17 18 void *Thread2(void *x) { 19 sleep(1); 20 pthread_mutex_lock(&Mtx); 21 Global = 43; 22 pthread_mutex_unlock(&Mtx); 23 return NULL; 24 } 25 26 int main() { 27 pthread_t t[2]; 28 pthread_create(&t[0], NULL, Thread1, NULL); 29 pthread_create(&t[1], NULL, Thread2, NULL); 30 pthread_join(t[0], NULL); 31 pthread_join(t[1], NULL); 32 pthread_mutex_destroy(&Mtx); 33 return 0; 34 } 35 36 // CHECK: WARNING: ThreadSanitizer: data race 37 // CHECK-NEXT: Atomic read of size 1 at {{.*}} by thread T2: 38 // CHECK-NEXT: #0 pthread_mutex_lock 39 // CHECK-NEXT: #1 Thread2{{.*}} {{.*}}race_on_mutex.c:20{{(:3)?}} ({{.*}}) 40 // CHECK: Previous write of size 1 at {{.*}} by thread T1: 41 // CHECK-NEXT: #0 pthread_mutex_init {{.*}} ({{.*}}) 42 // CHECK-NEXT: #1 Thread1{{.*}} {{.*}}race_on_mutex.c:11{{(:3)?}} ({{.*}}) 43