1 | #include <stdio.h>
|
---|
2 | #include <stdlib.h>
|
---|
3 | #include <clib/cfathread.h>
|
---|
4 |
|
---|
5 | extern "C" {
|
---|
6 | void _exit(int status);
|
---|
7 | }
|
---|
8 |
|
---|
9 | thread_local struct drand48_data buffer = { 0 };
|
---|
10 | int myrand() {
|
---|
11 | long int result;
|
---|
12 | lrand48_r(&buffer, &result);
|
---|
13 | return result;
|
---|
14 | }
|
---|
15 |
|
---|
16 |
|
---|
17 | enum Constants { blocked_size = 20 };
|
---|
18 | cfathread_t volatile blocked[blocked_size];
|
---|
19 |
|
---|
20 | void * Worker( void * ) {
|
---|
21 | for(int i = 0; i < 1000; i++) {
|
---|
22 | int idx = myrand() % blocked_size;
|
---|
23 | if(blocked[idx]) {
|
---|
24 | cfathread_t thrd = __atomic_exchange_n(&blocked[idx], NULL, __ATOMIC_SEQ_CST);
|
---|
25 | cfathread_unpark( thrd );
|
---|
26 | } else {
|
---|
27 | cfathread_t thrd = __atomic_exchange_n(&blocked[idx], cfathread_self(), __ATOMIC_SEQ_CST);
|
---|
28 | cfathread_unpark( thrd );
|
---|
29 | cfathread_park();
|
---|
30 | }
|
---|
31 | }
|
---|
32 | printf("Done\n");
|
---|
33 | return NULL;
|
---|
34 | }
|
---|
35 |
|
---|
36 | volatile bool stop;
|
---|
37 | void * Unparker( void * ) {
|
---|
38 | while(!stop) {
|
---|
39 | int idx = myrand() % blocked_size;
|
---|
40 | cfathread_t thrd = __atomic_exchange_n(&blocked[idx], NULL, __ATOMIC_SEQ_CST);
|
---|
41 | cfathread_unpark( thrd );
|
---|
42 | int r = myrand() % 20;
|
---|
43 | for( int i = 0; i < r; i++ ) {
|
---|
44 | cfathread_yield();
|
---|
45 | }
|
---|
46 | }
|
---|
47 | printf("Done Unparker\n");
|
---|
48 | return NULL;
|
---|
49 | }
|
---|
50 |
|
---|
51 |
|
---|
52 | int main() {
|
---|
53 | stop = false;
|
---|
54 | for(int i = 0; i < blocked_size; i++) {
|
---|
55 | blocked[i] = NULL;
|
---|
56 | }
|
---|
57 |
|
---|
58 | cfathread_cluster_t cl = cfathread_cluster_self();
|
---|
59 |
|
---|
60 | cfathread_cluster_add_worker( cl, NULL, NULL, NULL );
|
---|
61 | cfathread_cluster_add_worker( cl, NULL, NULL, NULL );
|
---|
62 | cfathread_cluster_add_worker( cl, NULL, NULL, NULL );
|
---|
63 | cfathread_t u;
|
---|
64 | cfathread_create( &u, NULL, Unparker, NULL );
|
---|
65 | {
|
---|
66 | cfathread_t t[20];
|
---|
67 | for(int i = 0; i < 20; i++) {
|
---|
68 | cfathread_create( &t[i], NULL, Worker, NULL );
|
---|
69 | }
|
---|
70 | for(int i = 0; i < 20; i++) {
|
---|
71 | cfathread_join( t[i], NULL );
|
---|
72 | }
|
---|
73 | }
|
---|
74 | stop = true;
|
---|
75 | cfathread_join(u, NULL);
|
---|
76 | fflush(stdout);
|
---|
77 | _exit(0);
|
---|
78 | }
|
---|