1 /* Test whether all data races are detected in a multithreaded program with
8 /***********************/
9 /* Include directives. */
10 /***********************/
21 /*********************/
22 /* Type definitions. */
23 /*********************/
34 /********************/
35 /* Local variables. */
36 /********************/
41 /*************************/
42 /* Function definitions. */
43 /*************************/
45 /** Single thread, which touches p->iterations elements of array p->array.
46 * Each modification of an element of p->array is a data race. */
47 static void* threadfunc(struct threadinfo
* p
)
50 int8_t* const array
= p
->array
;
51 pthread_barrier_t
* const b
= p
->b
;
53 printf("thread %lx iteration 0\n", (long) pthread_self());
54 pthread_barrier_wait(b
);
55 for (i
= 0; i
< p
->iterations
; i
++)
58 printf("thread %lx iteration %d; writing to %p\n",
59 (long) pthread_self(), i
+ 1, &array
[i
]);
61 pthread_barrier_wait(b
);
66 /** Actual test, consisting of nthread threads. */
67 static void barriers_and_races(const int nthread
, const int iterations
)
75 t
= malloc(nthread
* sizeof(struct threadinfo
));
76 array
= malloc(iterations
* sizeof(array
[0]));
79 printf("&array[0] = %p\n", array
);
81 pthread_barrier_init(&b
, 0, nthread
);
83 pthread_attr_init(&attr
);
84 res
= pthread_attr_setstacksize(&attr
, PTHREAD_STACK_MIN
+ 4096);
87 for (i
= 0; i
< nthread
; i
++)
91 t
[i
].iterations
= iterations
;
92 res
= pthread_create(&t
[i
].tid
, &attr
, (void*(*)(void*))threadfunc
, &t
[i
]);
94 fprintf(stderr
, "Could not create thread #%d (of %d): %s\n",
95 i
, nthread
, strerror(res
));
100 pthread_attr_destroy(&attr
);
102 for (i
= 0; i
< nthread
; i
++)
104 pthread_join(t
[i
].tid
, 0);
107 pthread_barrier_destroy(&b
);
113 int main(int argc
, char** argv
)
118 nthread
= (argc
> 1) ? atoi(argv
[1]) : 2;
119 iterations
= (argc
> 2) ? atoi(argv
[2]) : 3;
120 s_silent
= (argc
> 3) ? atoi(argv
[3]) : 0;
122 barriers_and_races(nthread
, iterations
);