1 |
#!/usr/bin/perl |
2 |
|
3 |
# the classical producer/consumer example, using semaphores |
4 |
# one process produces items, send s a signal. |
5 |
# another process waits for that signal and |
6 |
# consumed the item. |
7 |
|
8 |
use Coro; |
9 |
use Coro::Process; |
10 |
use Coro::Semaphore; |
11 |
|
12 |
my $produced = new Coro::Semaphore 0; |
13 |
my $finished = new Coro::Semaphore 0; |
14 |
|
15 |
async { |
16 |
for my $i (0..9) { |
17 |
print "produced $i\n"; |
18 |
push @buffer, $i; |
19 |
$produced->up; |
20 |
yield if @buffer > 5; # simulate memory pressure ;) |
21 |
} |
22 |
print "work done\n"; |
23 |
$finished->up; |
24 |
}; |
25 |
|
26 |
async { |
27 |
while () { |
28 |
$produced->down; |
29 |
my $i = shift @buffer; |
30 |
print "consumed $i\n"; |
31 |
} |
32 |
}; |
33 |
|
34 |
$finished->down; |
35 |
|
36 |
print "job finished\n"; |
37 |
|