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 extern "C" void AnnotateThreadName(const char *f, int l, const char *name);
19 
20 int Global;
21 
Thread1(void * x)22 void *Thread1(void *x) {
23   barrier_wait(&barrier);
24   AnnotateThreadName(__FILE__, __LINE__, "Thread1");
25   Global++;
26   return NULL;
27 }
28 
Thread2(void * x)29 void *Thread2(void *x) {
30 #if USE_PTHREAD_SETNAME_NP
31   tsan_pthread_setname_np(pthread_self(), "Thread2");
32 #else
33   AnnotateThreadName(__FILE__, __LINE__, "Thread2");
34 #endif
35   Global--;
36   barrier_wait(&barrier);
37   return NULL;
38 }
39 
main()40 int main() {
41   barrier_init(&barrier, 2);
42   pthread_t t[2];
43   pthread_create(&t[0], NULL, Thread1, NULL);
44   pthread_create(&t[1], NULL, Thread2, NULL);
45   pthread_join(t[0], NULL);
46   pthread_join(t[1], NULL);
47 }
48 
49 // CHECK: WARNING: ThreadSanitizer: data race
50 // CHECK:   Thread T1 'Thread1'
51 // CHECK:   Thread T2 'Thread2'
52