Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env perl
- # Solución para llenar 10 coches de políticos, en grupos de 4 del mismo partido o de 2 de cada partido.
- use warnings;
- use strict;
- use threads;
- use threads::shared;
- use Thread::Semaphore;
- my $s_mutex= Thread::Semaphore->new(1);
- my $s_PSOE= Thread::Semaphore->new(0);
- my $s_PP= Thread::Semaphore->new(0);
- my $PSOE :shared= 0;
- my $PP :shared= 0;
- my $coche= 1;
- srand();
- while(1) {
- if(&alea(1,2) == 1) {
- print"Ha llegado un político del PP\n";
- threads->create(\&PP);
- }else{
- print("Ha llegado un político del PSOE\n");
- threads->create(\&PSOE);
- }
- $PSOE++;
- $PP++;
- print("hay $PP políticos del PP esperando + y $PSOE políticos del PSOE esperando\n");
- &cochelleno();
- system("usleep", 2);
- }
- sub PSOE {
- $s_mutex->down();
- if ($PSOE == 3){
- $s_PSOE->up(3);
- $s_PSOE = 0;
- &cochelleno();
- } elsif ($PSOE > 0 && $PP > 1){
- $s_PP->up(2);
- $PSOE -= 1;
- $PP -= 2;
- &cochelleno();
- } elsif ($PSOE == 2 && $PP == 2){
- $s_PP->up();
- $s_PSOE->up();
- $PSOE -= 2;
- $PP -= 2;
- &cochelleno();
- } else {
- $PSOE++;
- $s_mutex->up();
- $s_PP->down();
- }
- }
- sub PP {
- $s_mutex->down();
- if ($PP == 3){
- $s_PP->up(3);
- $PP = 0;
- &cochelleno();
- } elsif ($PP > 0 && $PSOE > 1){
- $s_PP->up();
- $s_PSOE->up(2);
- $PP -= 1;
- $PSOE -= 2;
- &cochelleno();
- } else {
- $PP++;
- $s_mutex->up();
- $s_PSOE->down();
- }
- }
- sub cochelleno{
- if( (($s_PP == 3) && ($PSOE == 2)) || (($PSOE == 3) && ($PP == 2)) ){
- $PP= $PP - 2;
- $s_PP->up(2);
- $PSOE= $PSOE - 2;
- $s_PSOE->up(2);
- print"El coche está completamente lleno\n\n";
- $coche++;
- print"Hay + $coche coches completos\n\n";
- if($coche == 10){
- system(exit);
- }
- }elsif( ($PP == 2) && ($PSOE == 2) ) {
- $PP= $PP - 2;
- $s_PP->up(2);
- $PSOE= $PSOE - 2;
- $s_PSOE->up(2);
- print"El coche está completamente lleno\n\n";
- $coche++;
- print"Hay + $coche coches completos\n\n";
- if($coche == 10){
- system(exit);
- }
- }
- }
- sub alea {
- (my $min, my $max)= @_;
- return ($min+int(rand($max-$min+1)));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement