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