xref: /aosp_15_r20/external/compiler-rt/test/tsan/cond.c (revision 7c3d14c8b49c529e04be81a3ce6f5cc23712e4c6)
1*7c3d14c8STreehugger Robot // RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
2*7c3d14c8STreehugger Robot // CHECK-NOT: WARNING: ThreadSanitizer: data race
3*7c3d14c8STreehugger Robot // CHECK-NOT: ThreadSanitizer WARNING: double lock
4*7c3d14c8STreehugger Robot // CHECK-NOT: ThreadSanitizer WARNING: mutex unlock by another thread
5*7c3d14c8STreehugger Robot // CHECK: OK
6*7c3d14c8STreehugger Robot 
7*7c3d14c8STreehugger Robot #include <stdio.h>
8*7c3d14c8STreehugger Robot #include <stdlib.h>
9*7c3d14c8STreehugger Robot #include <pthread.h>
10*7c3d14c8STreehugger Robot 
11*7c3d14c8STreehugger Robot pthread_mutex_t m;
12*7c3d14c8STreehugger Robot pthread_cond_t c;
13*7c3d14c8STreehugger Robot int x;
14*7c3d14c8STreehugger Robot 
thr1(void * p)15*7c3d14c8STreehugger Robot void *thr1(void *p) {
16*7c3d14c8STreehugger Robot   int i;
17*7c3d14c8STreehugger Robot 
18*7c3d14c8STreehugger Robot   for (i = 0; i < 10; i += 2) {
19*7c3d14c8STreehugger Robot     pthread_mutex_lock(&m);
20*7c3d14c8STreehugger Robot     while (x != i)
21*7c3d14c8STreehugger Robot       pthread_cond_wait(&c, &m);
22*7c3d14c8STreehugger Robot     x = i + 1;
23*7c3d14c8STreehugger Robot     pthread_cond_signal(&c);
24*7c3d14c8STreehugger Robot     pthread_mutex_unlock(&m);
25*7c3d14c8STreehugger Robot   }
26*7c3d14c8STreehugger Robot   return 0;
27*7c3d14c8STreehugger Robot }
28*7c3d14c8STreehugger Robot 
thr2(void * p)29*7c3d14c8STreehugger Robot void *thr2(void *p) {
30*7c3d14c8STreehugger Robot   int i;
31*7c3d14c8STreehugger Robot 
32*7c3d14c8STreehugger Robot   for (i = 1; i < 10; i += 2) {
33*7c3d14c8STreehugger Robot     pthread_mutex_lock(&m);
34*7c3d14c8STreehugger Robot     while (x != i)
35*7c3d14c8STreehugger Robot       pthread_cond_wait(&c, &m);
36*7c3d14c8STreehugger Robot     x = i + 1;
37*7c3d14c8STreehugger Robot     pthread_mutex_unlock(&m);
38*7c3d14c8STreehugger Robot     pthread_cond_broadcast(&c);
39*7c3d14c8STreehugger Robot   }
40*7c3d14c8STreehugger Robot   return 0;
41*7c3d14c8STreehugger Robot }
42*7c3d14c8STreehugger Robot 
main()43*7c3d14c8STreehugger Robot int main() {
44*7c3d14c8STreehugger Robot   pthread_t th1, th2;
45*7c3d14c8STreehugger Robot 
46*7c3d14c8STreehugger Robot   pthread_mutex_init(&m, 0);
47*7c3d14c8STreehugger Robot   pthread_cond_init(&c, 0);
48*7c3d14c8STreehugger Robot   pthread_create(&th1, 0, thr1, 0);
49*7c3d14c8STreehugger Robot   pthread_create(&th2, 0, thr2, 0);
50*7c3d14c8STreehugger Robot   pthread_join(th1, 0);
51*7c3d14c8STreehugger Robot   pthread_join(th2, 0);
52*7c3d14c8STreehugger Robot   fprintf(stderr, "OK\n");
53*7c3d14c8STreehugger Robot }
54