1 |
root |
1.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 |
root |
1.2 |
my $produced = new Coro::Semaphore 0; |
13 |
root |
1.1 |
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 |
|
|
$idle; |
25 |
|
|
}; |
26 |
|
|
|
27 |
|
|
async { |
28 |
|
|
while () { |
29 |
|
|
$produced->down; |
30 |
|
|
my $i = shift @buffer; |
31 |
|
|
print "consumed $i\n"; |
32 |
|
|
} |
33 |
|
|
}; |
34 |
|
|
|
35 |
|
|
$finished->down; |
36 |
|
|
|
37 |
|
|
print "job finished\n"; |
38 |
|
|
|