Advertisement
Guest User

Untitled

a guest
Mar 15th, 2014
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #!/usr/bin/env perl
  2. # Solución para llenar 10 coches de políticos, en grupos de 4 del mismo partido o de 2 de cada partido.
  3.  
  4. use warnings;
  5. use strict;
  6. use threads;
  7. use threads::shared;
  8. use Thread::Semaphore;
  9.  
  10. my $s_mutex= Thread::Semaphore->new(1);
  11. my $s_PSOE= Thread::Semaphore->new(0);
  12. my $s_PP= Thread::Semaphore->new(0);
  13. my $PSOE :shared= 0;
  14. my $PP :shared= 0;
  15. my $coche= 1;
  16.  
  17. srand();
  18.  
  19. while(1) {
  20. if(&alea(1,2) == 1) {
  21. print"Ha llegado un político del PP\n";
  22. threads->create(\&PP);
  23.  
  24. }else{
  25. print("Ha llegado un político del PSOE\n");
  26. threads->create(\&PSOE);
  27. }
  28.  
  29. $PSOE++;
  30. $PP++;
  31. print("hay $PP políticos del PP esperando + y $PSOE políticos del PSOE esperando\n");
  32. &cochelleno();
  33. system("usleep", 2);
  34. }
  35.  
  36. sub PSOE {
  37. $s_mutex->down();
  38. if ($PSOE == 3){
  39. $s_PSOE->up(3);
  40. $s_PSOE = 0;
  41. &cochelleno();
  42.  
  43. } elsif ($PSOE > 0 && $PP > 1){
  44. $s_PP->up(2);
  45. $PSOE -= 1;
  46. $PP -= 2;
  47. &cochelleno();
  48.  
  49. } elsif ($PSOE == 2 && $PP == 2){
  50. $s_PP->up();
  51. $s_PSOE->up();
  52. $PSOE -= 2;
  53. $PP -= 2;
  54. &cochelleno();
  55.  
  56. } else {
  57. $PSOE++;
  58. $s_mutex->up();
  59. $s_PP->down();
  60. }
  61. }
  62.  
  63. sub PP {
  64. $s_mutex->down();
  65. if ($PP == 3){
  66. $s_PP->up(3);
  67. $PP = 0;
  68. &cochelleno();
  69.  
  70. } elsif ($PP > 0 && $PSOE > 1){
  71. $s_PP->up();
  72. $s_PSOE->up(2);
  73. $PP -= 1;
  74. $PSOE -= 2;
  75. &cochelleno();
  76.  
  77.  
  78. } else {
  79. $PP++;
  80. $s_mutex->up();
  81. $s_PSOE->down();
  82. }
  83. }
  84.  
  85. sub cochelleno{
  86. if( (($s_PP == 3) && ($PSOE == 2)) || (($PSOE == 3) && ($PP == 2)) ){
  87. $PP= $PP - 2;
  88. $s_PP->up(2);
  89. $PSOE= $PSOE - 2;
  90. $s_PSOE->up(2);
  91. print"El coche está completamente lleno\n\n";
  92. $coche++;
  93. print"Hay + $coche coches completos\n\n";
  94. if($coche == 10){
  95. system(exit);
  96. }
  97.  
  98. }elsif( ($PP == 2) && ($PSOE == 2) ) {
  99. $PP= $PP - 2;
  100. $s_PP->up(2);
  101. $PSOE= $PSOE - 2;
  102. $s_PSOE->up(2);
  103. print"El coche está completamente lleno\n\n";
  104. $coche++;
  105. print"Hay + $coche coches completos\n\n";
  106. if($coche == 10){
  107. system(exit);
  108. }
  109. }
  110. }
  111.  
  112. sub alea {
  113. (my $min, my $max)= @_;
  114. return ($min+int(rand($max-$min+1)));
  115. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement