• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Mini-benchmark for tsan: shared memory reads.
2 #include <pthread.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <assert.h>
6 
7 int len;
8 int *a;
9 const int kNumIter = 1000;
10 
11 __attribute__((noinline))
Run(int idx)12 void Run(int idx) {
13   for (int i = 0, n = len; i < n; i++)
14     if (a[i] != i) abort();
15 }
16 
Thread(void * arg)17 void *Thread(void *arg) {
18   long idx = (long)arg;
19   printf("Thread %ld started\n", idx);
20   for (int i = 0; i < kNumIter; i++)
21     Run(idx);
22   printf("Thread %ld done\n", idx);
23   return 0;
24 }
25 
main(int argc,char ** argv)26 int main(int argc, char **argv) {
27   int n_threads = 0;
28   if (argc != 3) {
29     n_threads = 4;
30     len = 1000000;
31   } else {
32     n_threads = atoi(argv[1]);
33     assert(n_threads > 0 && n_threads <= 32);
34     len = atoi(argv[2]);
35   }
36   printf("%s: n_threads=%d len=%d iter=%d\n",
37          __FILE__, n_threads, len, kNumIter);
38   a = new int[len];
39   for (int i = 0, n = len; i < n; i++)
40     a[i] = i;
41   pthread_t *t = new pthread_t[n_threads];
42   for (int i = 0; i < n_threads; i++) {
43     pthread_create(&t[i], 0, Thread, (void*)i);
44   }
45   for (int i = 0; i < n_threads; i++) {
46     pthread_join(t[i], 0);
47   }
48   delete [] t;
49   delete [] a;
50   return 0;
51 }
52