source: tests/concurrency/clib.c@ bada452

Last change on this file since bada452 was c26bea2a, checked in by Peter A. Buhr <pabuhr@…>, 2 years ago

first attempt at renaming directory tests/concurrent to tests/concurrency to harmonize with other concurrency directory names

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