-
Notifications
You must be signed in to change notification settings - Fork 2
/
03.Producer-Consumer.ino
106 lines (89 loc) · 2.34 KB
/
03.Producer-Consumer.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
This example demonstrates how asymmetric coroutines can be used to
solve a well known "producer-consumer" problem.
Coroutines communicate using the send() and receive() functions.
send() passes a value to the consumer and resumes it, receive() gets
value from the producer and returns control back to it. These actions
are repeated forever.
It is a consumer-driven design because the program starts by calling
the consumer. When the consumer needs an item, it resumes the
producer, which runs until it has an item to give to the consumer, and
then pauses until the consumer restarts it again.
When being uploaded to an Arduino board, this sketch produces a pair
of messages via serial port every one second in the following format:
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Produced: 4
...
***
Author: Artem Boldariev <artem@boldariev.com>
This example code is in the public domain.
See UNLICENSE.txt in the examples directory for license details.
*/
#include <avrcontext_arduino.h>
#define STACK_SIZE 128
static avr_coro_t producer, consumer;
static uint8_t producer_stack[STACK_SIZE], consumer_stack[STACK_SIZE];
static void send(avr_coro_t *to, int value)
{
void *data = &value;
avr_coro_resume(to, &data);
}
static int receive(avr_coro_t *self)
{
int *data = NULL;
avr_coro_yield(self, (void **)&data);
return *data;
}
static void *producer_func(avr_coro_t *, void *data)
{
avr_coro_t *cons = (avr_coro_t *)data;
int num = 0;
for (;;)
{
Serial.print(F("Produced: "));
Serial.println(num);
send(cons, num);
num++;
delay(1000);
}
return NULL;
}
static void *consumer_func(avr_coro_t *self, void *)
{
for (;;)
{
int received = receive(self);
Serial.print(F("Consumed: "));
Serial.println(received);
}
return NULL;
}
void setup()
{
void *data;
avr_coro_init(&producer,
&producer_stack[0], STACK_SIZE,
producer_func);
avr_coro_init(&consumer,
&consumer_stack[0], STACK_SIZE,
consumer_func);
Serial.begin(9600);
while(!Serial)
;
avr_coro_resume(&consumer, NULL);
data = &consumer;
avr_coro_resume(&producer, &data);
// unreachable
}
void loop()
{
// unreachable
}