Debian Codegraph @

tests/weaver.c

raw
1 #define _GNU_SOURCE
2
3 #include <stdio.h>
4 #include <sys/prctl.h>
5 #include <pthread.h>
6 #include <unistd.h>
7
8 #include "./weaver.h"
9 #include "../libcap/execable.h"
10
11 static pthread_mutex_t mu;
12 static pthread_cond_t cond; /* this is only used to wait on 'state' changes */
13 static int primed = 0;
14 static int counter = 0;
15 static int total = 0;
16 static int trigger = 0; /* 0=wait, 1=tick, 2=exit */
17
18 static void *run_thread(void *ignored)
19 {
20 pthread_mutex_lock(&mu);
21 do {
22 primed++;
23 while (trigger == 0) {
24 pthread_cond_signal(&cond);
25 pthread_cond_wait(&cond, &mu);
26 }
27 if (trigger == 1) {
28 counter++;
29 total += prctl(PR_GET_KEEPCAPS, 0, 0, 0, 0, 0)+2;
30 primed--;
31 while (trigger == 1) {
32 pthread_cond_signal(&cond);
33 pthread_cond_wait(&cond, &mu);
34 }
35 }
36 } while (trigger != 2);
37 pthread_cond_signal(&cond);
38 pthread_mutex_unlock(&mu);
39 return NULL;
40 }
41
42 pthread_t weaver_thread(void)
43 {
44 pthread_t th;
45 pthread_create(&th, NULL, run_thread, NULL);
46 return th;
47 }
48
49 void weaver_setup(void)
50 {
51 pthread_mutex_init(&mu, NULL);
52 pthread_cond_init(&cond, NULL);
53 }
54
55 int weaver_waitforit(int n)
56 {
57 pthread_mutex_lock(&mu);
58 counter = 0;
59 total = 0;
60 pthread_mutex_unlock(&mu);
61 /* be sure that the above happens before triggering */
62 pthread_mutex_lock(&mu);
63 while (primed < n) {
64 pthread_cond_signal(&cond);
65 pthread_cond_wait(&cond, &mu);
66 }
67 trigger = 1;
68 while (counter < n) {
69 pthread_cond_signal(&cond);
70 pthread_cond_wait(&cond, &mu);
71 }
72 trigger = 0;
73 pthread_cond_signal(&cond);
74 pthread_mutex_unlock(&mu);
75 return total;
76 }
77
78 void weaver_terminate(void)
79 {
80 pthread_mutex_lock(&mu);
81 trigger = 2;
82 pthread_cond_signal(&cond);
83 pthread_mutex_unlock(&mu);
84 }
85
86 #define N_THREADS 10
87
88 SO_MAIN(int argc, char **argv) {
89 int i;
90 pthread_t arr[N_THREADS];
91
92 weaver_setup();
93 for (i = 0; i < N_THREADS; i++) {
94 long int val = !(i & 1);
95 prctl(PR_SET_KEEPCAPS, val, 0, 0, 0, 0, 0);
96 arr[i] = weaver_thread();
97 }
98 int n = weaver_waitforit(N_THREADS);
99 weaver_terminate();
100 for (i = 0; i < N_THREADS; i++) {
101 pthread_join(arr[i], NULL);
102 }
103 if (n != 25) {
104 printf("FAILED: got=%d, want=25\n", n);
105 exit(1);
106 }
107 printf("PASSED\n");
108 }