1 | #include <fstream.hfa> |
---|
2 | #include <coroutine.hfa> |
---|
3 | #include <stdlib.hfa> // random |
---|
4 | #include <unistd.h> // getpid |
---|
5 | coroutine Cons; // forward |
---|
6 | int delivery( Cons & cons, int p1, int p2 ); |
---|
7 | void stop( Cons & cons ); |
---|
8 | |
---|
9 | coroutine Prod { |
---|
10 | Cons & c; |
---|
11 | int N, money, receipt; |
---|
12 | }; |
---|
13 | void main( Prod & prod ) with( prod ) { // starter ::main |
---|
14 | // 1st resume starts here |
---|
15 | for ( i; N ) { // N pairs of values |
---|
16 | int p1 = random( 100 ), p2 = random( 100 ); |
---|
17 | sout | p1 | " " | p2; |
---|
18 | int status = delivery( c, p1, p2 ); |
---|
19 | sout | " $" | money | nl | status; |
---|
20 | receipt += 1; |
---|
21 | } |
---|
22 | stop( c ); |
---|
23 | sout | "prod stops"; |
---|
24 | } |
---|
25 | int payment( Prod & prod, int m ) with(prod) { |
---|
26 | money = m; |
---|
27 | resume( prod ); // main 1st time, then |
---|
28 | return receipt; // prod in delivery |
---|
29 | } |
---|
30 | void start( Prod & prod, int N, Cons &c ) { |
---|
31 | &prod.c = &c; |
---|
32 | prod.[N, receipt] = [N, 0]; |
---|
33 | resume( prod ); // activate main |
---|
34 | } |
---|
35 | coroutine Cons { |
---|
36 | Prod & p; |
---|
37 | int p1, p2, status; |
---|
38 | bool done; |
---|
39 | }; |
---|
40 | void ?{}( Cons & cons, Prod & p ) { |
---|
41 | &cons.p = &p; |
---|
42 | cons.[status, done ] = [0, false]; |
---|
43 | } |
---|
44 | void ^?{}( Cons & cons ) {} |
---|
45 | void main( Cons & cons ) with( cons ) { // starter prod |
---|
46 | // 1st resume starts here |
---|
47 | int money = 1, receipt; |
---|
48 | for ( ; ! done; ) { |
---|
49 | sout | p1 | " " | p2 | nl | " $" | money; |
---|
50 | status += 1; |
---|
51 | receipt = payment( p, money ); |
---|
52 | sout | " #" | receipt; |
---|
53 | money += 1; |
---|
54 | } |
---|
55 | sout | "cons stops"; |
---|
56 | } |
---|
57 | int delivery( Cons & cons, int p1, int p2 ) { |
---|
58 | cons.[p1, p2] = [p1, p2]; |
---|
59 | resume( cons ); // main 1st time, then |
---|
60 | return cons.status; // cons in payment |
---|
61 | } |
---|
62 | void stop( Cons & cons ) { |
---|
63 | cons.done = true; |
---|
64 | resume( cons ); // activate payment |
---|
65 | } |
---|
66 | int main() { |
---|
67 | Prod prod; |
---|
68 | Cons cons = { prod }; |
---|
69 | srandom( getpid() ); |
---|
70 | start( prod, 5, cons ); |
---|
71 | } |
---|
72 | |
---|
73 | // Local Variables: // |
---|
74 | // tab-width: 4 // |
---|
75 | // compile-command: "cfa ProdCons.cfa" // |
---|
76 | // End: // |
---|