source: tests/coroutine/prodcons.cfa@ 2fa0237

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

update file names in emacs compile directive

  • Property mode set to 100644
File size: 2.3 KB
Line 
1//
2// Cforall Version 1.0.0 Copyright (C) 2017 University of Waterloo
3//
4// The contents of this file are covered under the licence agreement in the
5// file "LICENCE" distributed with Cforall.
6//
7// prodcons.c --
8//
9// Author : Peter A. Buhr
10// Created On : Mon Sep 18 12:23:39 2017
11// Last Modified By : Peter A. Buhr
12// Last Modified On : Fri Mar 22 13:41:10 2019
13// Update Count : 54
14//
15
16#include <fstream.hfa>
17#include <coroutine.hfa>
18#include <stdlib.hfa> // random
19#include <unistd.h> // getpid
20
21coroutine Cons; // forward
22int delivery( Cons & cons, int p1, int p2 );
23void stop( Cons & cons );
24
25coroutine Prod {
26 Cons & c;
27 int N, money, receipt;
28};
29void main( Prod & prod ) with( prod ) { // starter ::main
30 // 1st resume starts here
31 for ( i; N ) { // N pairs of values
32 int p1 = random( 100 ), p2 = random( 100 );
33 sout | p1 | " " | p2;
34 int status = delivery( c, p1, p2 );
35 sout | " $" | money | nl | status;
36 receipt += 1;
37 }
38 stop( c );
39 sout | "prod stops";
40}
41int payment( Prod & prod, int money ) {
42 prod.money = money;
43 resume( prod ); // main 1st time, then
44 return prod.receipt; // prod in delivery
45}
46void start( Prod & prod, int N, Cons &c ) {
47 &prod.c = &c;
48 prod.[N, receipt] = [N, 0];
49 resume( prod ); // activate main
50}
51
52coroutine Cons {
53 Prod & p;
54 int p1, p2, status;
55 bool done;
56};
57void ?{}( Cons & cons, Prod & p ) {
58 &cons.p = &p;
59 cons.[status, done ] = [0, false];
60}
61void ^?{}( Cons & cons ) {}
62void main( Cons & cons ) with( cons ) { // starter prod
63 // 1st resume starts here
64 int money = 1, receipt;
65 for ( ; ! done; ) {
66 sout | p1 | " " | p2 | nl | " $" | money;
67 status += 1;
68 receipt = payment( p, money );
69 sout | " #" | receipt;
70 money += 1;
71 }
72 sout | "cons stops";
73}
74int delivery( Cons & cons, int p1, int p2 ) {
75 cons.[p1, p2] = [p1, p2];
76 resume( cons ); // main 1st time, then
77 return cons.status; // cons in payment
78}
79void stop( Cons & cons ) {
80 cons.done = true;
81 resume( cons ); // activate payment
82}
83int main() {
84 Prod prod;
85 Cons cons = { prod };
86 srandom( /* getpid() */ 103 ); // fixed seed for testing
87 start( prod, 5, cons );
88 sout | "main stops";
89}
90
91// Local Variables: //
92// tab-width: 4 //
93// compile-command: "cfa prodcons.cfa" //
94// End: //
Note: See TracBrowser for help on using the repository browser.