Múltiples Lectores

También la lectura parece ocurrir en exclusión mutua como muestra la ejecución del siguiente código. En este programa los papeles se invierten con respecto al anterior: el padre escribe y los hijos permanecen a la escucha leyendo desde el canal abierto. Cuando reciben un mensaje lo vuelcan por STDOUT.

lhp@nereida:~/Lperl/src/perl_networking/ch2$ cat -n pipemultread.pl
 1  #!/usr/bin/perl -w
 2  use strict;
 3  use IO::Handle;
 4
 5  my $np = (shift || 2);
 6  my $last = $np-1;
 7  my $i;
 8
 9  pipe(my $READER, my $WRITER) or die "Can't open pipe: $!\n";
10
11  create_child($_, \&task, "you", "are", $_) for (0..$last);
12  close($READER);
13  $WRITER->autoflush();
14  for $i (1..2*$np) {
15    print $WRITER "Message number $i From Father to Child\n";
16  }
17  for $i (1..$np) {
18    print $WRITER "finish\n";
19    wait();
20  }
21
22  sub create_child {
23    my $id = shift;
24    my $task = shift;
25    my @args = @_;
26
27    my $pid;
28
29    return $pid if $pid = fork();
30    die "Cannot fork $!" unless defined $pid;
31    close($WRITER);
32    my $result = task->($id, @args); # do something
33    exit;
34  }
35
36  sub task {
37    my $id = shift;
38    my @args = @_;
39
40    print "$id: Father pass me: @args\n";
41    {
42      my $message = <$READER>;
43      print "$id: Received $message";
44      last if ($message eq "finish\n");
45      redo;
46    }
47  }

Se muestra el resultado de dos ejecuciones. Los hijos reciben los mensajes completos. Parece ser no determinístico quién lee desde el canal.

hp@nereida:~/Lperl/src/perl_networking/ch2$ perl pipemultread.pl
0: Father pass me: you are 0
1: Father pass me: you are 1
1: Received Message number 1 From Father to Child
1: Received Message number 2 From Father to Child
1: Received Message number 3 From Father to Child
1: Received Message number 4 From Father to Child
1: Received finish
0: Received finish
lhp@nereida:~/Lperl/src/perl_networking/ch2$ perl pipemultread.pl
0: Father pass me: you are 0
1: Father pass me: you are 1
1: Received Message number 1 From Father to Child
0: Received Message number 2 From Father to Child
0: Received Message number 3 From Father to Child
0: Received Message number 4 From Father to Child
0: Received finish
1: Received finish

Ejercicio 4.1.1   ¿Que ocurre si movemos el close(READER) de la línea 12 a la línea 10?

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