1 // RUN: %clangxx_tsan -O1 %s -o %t && %deflake %run %t | FileCheck %s
2 #include "test.h"
3 
4 #if defined(__linux__)
5 #define USE_PTHREAD_SETNAME_NP __GLIBC_PREREQ(2, 12)
6 #define tsan_pthread_setname_np pthread_setname_np
7 #elif defined(__FreeBSD__)
8 #include <pthread_np.h>
9 #define USE_PTHREAD_SETNAME_NP 1
10 #define tsan_pthread_setname_np pthread_set_name_np
11 #elif defined(__NetBSD__)
12 #define USE_PTHREAD_SETNAME_NP 1
13 #define tsan_pthread_setname_np(a, b) pthread_setname_np((a), "%s", (void *)(b))
14 #else
15 #define USE_PTHREAD_SETNAME_NP 0
16 #endif
17 
18 int Global;
19 
Thread1(void * x)20 void *Thread1(void *x) {
21   barrier_wait(&barrier);
22   AnnotateThreadName(__FILE__, __LINE__, "Thread1");
23   Global++;
24   return NULL;
25 }
26 
Thread2(void * x)27 void *Thread2(void *x) {
28 #if USE_PTHREAD_SETNAME_NP
29   tsan_pthread_setname_np(pthread_self(), "Thread2");
30 #else
31   AnnotateThreadName(__FILE__, __LINE__, "Thread2");
32 #endif
33   Global--;
34   barrier_wait(&barrier);
35   return NULL;
36 }
37 
main()38 int main() {
39   barrier_init(&barrier, 2);
40   pthread_t t[2];
41   pthread_create(&t[0], NULL, Thread1, NULL);
42   pthread_create(&t[1], NULL, Thread2, NULL);
43   pthread_join(t[0], NULL);
44   pthread_join(t[1], NULL);
45 }
46 
47 // CHECK: WARNING: ThreadSanitizer: data race
48 // CHECK:   Thread T1 'Thread1'
49 // CHECK:   Thread T2 'Thread2'
50