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