Permalink
Browse files

Add Producer-Consumer example

  • Loading branch information...
1 parent b86b6e8 commit 66b6c19aeddd2e579c5e75350026d4143425b3dc @tadzik committed Dec 18, 2012
Showing with 43 additions and 0 deletions.
  1. +43 −0 examples/producer-consumer.pl
View
43 examples/producer-consumer.pl
@@ -0,0 +1,43 @@
+use lib 'lib';
+use Threads;
+use Semaphore;
+
+my @elements;
+my $free-slots = Semaphore.new(value => 10); # 10 remaining slots
+my $full-slots = Semaphore.new(value => 0); # 10 remaining slots
+
+sub produce($id) {
+ my $i = 0;
+ loop {
+ note "Producer $id waiting for an empty slot";
+ $free-slots.wait; # acquire an empty slot
+ note "Producer $id adding element $i";
+ @elements.push: $i;
+ $i++;
+ note "Now present {+@elements} elements";
+ $full-slots.post; # there is now one more full slot
+ 1;
+ }
+}
+
+sub consume($id) {
+ loop {
+ note "Consumer $id waiting for a full slot";
+ $full-slots.wait; # acquire a full slot
+ my $a = @elements.shift;
+ note "Consumer $id eating $a";
+ $free-slots.post; # there is now one more free slot
+ 1;
+ }
+}
+
+for 1..5 -> $i {
+ async sub { produce($i) }
+}
+
+for 5..10 -> $i {
+ async sub { consume($i) }
+}
+
+sleep 5;
+exit;

0 comments on commit 66b6c19

Please sign in to comment.