[bb662027] | 1 | #include <stdio.h>
|
---|
| 2 | #include <stdlib.h>
|
---|
[df65c0c] | 3 | #include <clib/cfathread.h>
|
---|
| 4 |
|
---|
| 5 | extern "C" {
|
---|
| 6 | void _exit(int status);
|
---|
| 7 | }
|
---|
[bb662027] | 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 |
|
---|
[df65c0c] | 20 | void * Worker( void * ) {
|
---|
[bb662027] | 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 {
|
---|
[df65c0c] | 27 | cfathread_t thrd = __atomic_exchange_n(&blocked[idx], cfathread_self(), __ATOMIC_SEQ_CST);
|
---|
[bb662027] | 28 | cfathread_unpark( thrd );
|
---|
| 29 | cfathread_park();
|
---|
| 30 | }
|
---|
| 31 | }
|
---|
| 32 | printf("Done\n");
|
---|
[df65c0c] | 33 | return NULL;
|
---|
[bb662027] | 34 | }
|
---|
| 35 |
|
---|
| 36 | volatile bool stop;
|
---|
[df65c0c] | 37 | void * Unparker( void * ) {
|
---|
[bb662027] | 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");
|
---|
[df65c0c] | 48 | return NULL;
|
---|
[bb662027] | 49 | }
|
---|
| 50 |
|
---|
| 51 |
|
---|
| 52 | int main() {
|
---|
| 53 | stop = false;
|
---|
| 54 | for(int i = 0; i < blocked_size; i++) {
|
---|
| 55 | blocked[i] = NULL;
|
---|
| 56 | }
|
---|
| 57 |
|
---|
[df65c0c] | 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 );
|
---|
[bb662027] | 65 | {
|
---|
| 66 | cfathread_t t[20];
|
---|
| 67 | for(int i = 0; i < 20; i++) {
|
---|
[df65c0c] | 68 | cfathread_create( &t[i], NULL, Worker, NULL );
|
---|
[bb662027] | 69 | }
|
---|
| 70 | for(int i = 0; i < 20; i++) {
|
---|
[df65c0c] | 71 | cfathread_join( t[i], NULL );
|
---|
[bb662027] | 72 | }
|
---|
| 73 | }
|
---|
| 74 | stop = true;
|
---|
[df65c0c] | 75 | cfathread_join(u, NULL);
|
---|
| 76 | fflush(stdout);
|
---|
| 77 | _exit(0);
|
---|
[bb662027] | 78 | }
|
---|