ADT
arm-eh
ast-experimental
enum
forall-pointer-decay
jacob/cs343-translation
new-ast-unique-expr
pthread-emulation
qualifiedEnum
Last change
on this file since 77ff383 was bb662027, checked in by Thierry Delisle <tdelisle@…>, 5 years ago |
Added cfathread C library which encapsulates a small part of libcfa threads in a C interface.
|
-
Property mode
set to
100644
|
File size:
1.4 KB
|
Line | |
---|
1 | #include <clib/cfathread.h>
|
---|
2 |
|
---|
3 | #include <stdio.h>
|
---|
4 | #include <stdlib.h>
|
---|
5 |
|
---|
6 | thread_local struct drand48_data buffer = { 0 };
|
---|
7 | int myrand() {
|
---|
8 | long int result;
|
---|
9 | lrand48_r(&buffer, &result);
|
---|
10 | return result;
|
---|
11 | }
|
---|
12 |
|
---|
13 |
|
---|
14 | enum Constants { blocked_size = 20 };
|
---|
15 | cfathread_t volatile blocked[blocked_size];
|
---|
16 |
|
---|
17 | void Worker( cfathread_t this ) {
|
---|
18 | for(int i = 0; i < 1000; i++) {
|
---|
19 | int idx = myrand() % blocked_size;
|
---|
20 | if(blocked[idx]) {
|
---|
21 | cfathread_t thrd = __atomic_exchange_n(&blocked[idx], NULL, __ATOMIC_SEQ_CST);
|
---|
22 | cfathread_unpark( thrd );
|
---|
23 | } else {
|
---|
24 | cfathread_t thrd = __atomic_exchange_n(&blocked[idx], this, __ATOMIC_SEQ_CST);
|
---|
25 | cfathread_unpark( thrd );
|
---|
26 | cfathread_park();
|
---|
27 | }
|
---|
28 | }
|
---|
29 | printf("Done\n");
|
---|
30 | }
|
---|
31 |
|
---|
32 | volatile bool stop;
|
---|
33 | void Unparker( cfathread_t this ) {
|
---|
34 | while(!stop) {
|
---|
35 | int idx = myrand() % blocked_size;
|
---|
36 | cfathread_t thrd = __atomic_exchange_n(&blocked[idx], NULL, __ATOMIC_SEQ_CST);
|
---|
37 | cfathread_unpark( thrd );
|
---|
38 | int r = myrand() % 20;
|
---|
39 | for( int i = 0; i < r; i++ ) {
|
---|
40 | cfathread_yield();
|
---|
41 | }
|
---|
42 | }
|
---|
43 | printf("Done Unparker\n");
|
---|
44 | }
|
---|
45 |
|
---|
46 |
|
---|
47 | int main() {
|
---|
48 | stop = false;
|
---|
49 | for(int i = 0; i < blocked_size; i++) {
|
---|
50 | blocked[i] = NULL;
|
---|
51 | }
|
---|
52 |
|
---|
53 | cfathread_setproccnt( 4 );
|
---|
54 | cfathread_t u = cfathread_create( Unparker );
|
---|
55 | {
|
---|
56 | cfathread_t t[20];
|
---|
57 | for(int i = 0; i < 20; i++) {
|
---|
58 | t[i] = cfathread_create( Worker );
|
---|
59 | }
|
---|
60 | for(int i = 0; i < 20; i++) {
|
---|
61 | cfathread_join( t[i] );
|
---|
62 | }
|
---|
63 | }
|
---|
64 | stop = true;
|
---|
65 | cfathread_join(u);
|
---|
66 | cfathread_setproccnt( 1 );
|
---|
67 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.