Debian Codegraph @

testsuite/libffi.threads/tsan.c

raw
1 /* { dg-do run } */
2
3 #include "ffitest.h"
4
5 #include <pthread.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8
9 #define NUM_THREADS 20
10
11 #ifdef _POSIX_BARRIERS
12 pthread_barrier_t barrier;
13 #endif
14
15 typedef float (*callback_fn)(float, float);
16
17 void callback(ffi_cif *cif __UNUSED__, void *ret, void **args, void *userdata __UNUSED__) {
18 float a = *(float *)args[0];
19 float b = *(float *)args[1];
20 *(float *)ret = a / 2 + b / 2;
21 }
22
23 void *thread_func(void *arg) {
24 #ifdef _POSIX_BARRIERS
25 pthread_barrier_wait(&barrier);
26 #endif
27
28 ffi_cif cif;
29 ffi_type *args[2] = { &ffi_type_float, &ffi_type_float };
30
31 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_float, args) != FFI_OK) {
32 fprintf(stderr, "ffi_prep_cif failed\n");
33 return NULL;
34 }
35
36 ffi_closure *closure = ffi_closure_alloc(sizeof(ffi_closure), (void **)&arg);
37
38 if (ffi_prep_closure_loc(closure, &cif, callback, NULL, arg) != FFI_OK) {
39 fprintf(stderr, "ffi_prep_closure_loc failed\n");
40 return NULL;
41 }
42
43 callback_fn fn = (callback_fn)arg;
44 (void) fn(4.0f, 6.0f);
45
46 ffi_closure_free(closure);
47 return NULL;
48 }
49
50 int main() {
51 pthread_t threads[NUM_THREADS];
52
53 #ifdef _POSIX_BARRIERS
54 pthread_barrier_init(&barrier, NULL, NUM_THREADS);
55 #endif
56
57 for (int i = 0; i < NUM_THREADS; ++i) {
58 if (pthread_create(&threads[i], NULL, thread_func, NULL) != 0) {
59 perror("pthread_create");
60 exit(EXIT_FAILURE);
61 }
62 }
63
64 for (int i = 0; i < NUM_THREADS; ++i) {
65 pthread_join(threads[i], NULL);
66 }
67
68 #ifdef _POSIX_BARRIERS
69 pthread_barrier_destroy(&barrier);
70 #endif
71
72 printf("Completed\n");
73 return 0;
74 }