• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
2 // CHECK-NOT: ThreadSanitizer: data race
3 // CHECK: DONE
4 
5 // pthread barriers are not available on OS X
6 // UNSUPPORTED: darwin
7 
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <pthread.h>
11 #include <unistd.h>
12 
13 const int kSize = 4;
14 volatile int kIter = 10;  // prevent unwinding
15 int data[2][kSize];
16 pthread_barrier_t barrier;
17 
thr(void * p)18 void *thr(void *p) {
19   int idx = (int)(long)p;
20   for (int i = 0; i < kIter; i++) {
21     int *prev = data[i % 2];
22     int *curr = data[(i + 1) % 2];
23     int left = idx - 1 >= 0 ? prev[idx - 1] : 0;
24     int right = idx + 1 < kSize ? prev[idx + 1] : 0;
25     curr[idx] = (left + right) / 2;
26     pthread_barrier_wait(&barrier);
27   }
28   return 0;
29 }
30 
main()31 int main() {
32   pthread_barrier_init(&barrier, 0, kSize);
33   pthread_t th[kSize];
34   for (int i = 0; i < kSize; i++)
35     pthread_create(&th[i], 0, thr, (void*)(long)i);
36   for (int i = 0; i < kSize; i++)
37     pthread_join(th[i], 0);
38   pthread_barrier_destroy(&barrier);
39   fprintf(stderr, "DONE\n");
40 }
41