Semáforos

El módulo Coro::Semaphore proporciona objetos semáforos con contador. El contador indica el número de de corutinas clientes que pueden compartir el recurso antes de que se bloquee.

pp2@nereida:~/src/perl/coro$ cat -n prodconssemaphor.pl
 1  #!/usr/bin/perl
 2  use warnings;
 3  use strict;
 4
 5  use Coro;
 6  use Coro::Semaphore;
 7
 8  my @buffer;
 9
10  my $produced = Coro::Semaphore->new(0);
11  my $finished = Coro::Semaphore->new(0);
12
13  async {
14    for my $i (0..9) {
15      print "Produced $i\n";
16      push @buffer, $i;
17      $produced->up;
18      cede if @buffer > 5;
19    }
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";

pp2@nereida:~/src/perl/coro$ prodconssemaphor.pl
Produced 0
Produced 1
Produced 2
Produced 3
Produced 4
Produced 5
Consumed 0
Consumed 1
Consumed 2
Consumed 3
Consumed 4
Consumed 5
Produced 6
Produced 7
Produced 8
Produced 9
Work done
Consumed 6
Consumed 7
Consumed 8
Consumed 9
Job finished

Casiano Rodríguez León
Licencia de Creative Commons
Programación Distribuida y Mejora del Rendimiento
por Casiano Rodríguez León is licensed under a Creative Commons Reconocimiento 3.0 Unported License.

Permissions beyond the scope of this license may be available at http://campusvirtual.ull.es/ocw/course/view.php?id=44.
2012-06-19