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