Advertisement
Fhernd

UsoSincronizacionSemaphore.cs

Jul 23rd, 2014
2,668
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.CSharp.Cap04.R0410
  5. {
  6.     public sealed class UsoSincronizacionSemaphore
  7.     {
  8.         // Representa una instancia de Semaphore:
  9.         private static Semaphore semaforo;
  10.        
  11.         // Intervalo de orden de la salida:
  12.         private static int _intervalo;
  13.        
  14.         public static void Main()
  15.         {
  16.             Console.Title = "Uso Sincronización Semáforo";
  17.             Console.WriteLine ();
  18.            
  19.             // Crea una instancia de Semaphore>
  20.             semaforo = new Semaphore(0, 3);
  21.            
  22.             // Crea hasta 5 threads:
  23.             for (int i = 1; i <= 5; ++i)
  24.             {
  25.                 Thread t = new
  26.                     Thread(new ParameterizedThreadStart (Tarea));
  27.                
  28.                 t.Start (i);
  29.             }
  30.            
  31.             // Suspensión por 0.5 segundos para dejar que todos los
  32.             // threads entren en el semáforo:
  33.             Thread.Sleep (500);
  34.            
  35.             // Completa el semáforo (atención de todos los threads):
  36.             Console.WriteLine ("Invocación de semaforo.Release(3).");
  37.             semaforo.Release(3);
  38.            
  39.             Console.WriteLine ("\n`Main` ha finalizado.\n");
  40.         }
  41.        
  42.         private static void Tarea(object numero)
  43.         {
  44.             // Cada thread solicita el paso al objeto Semaphore:
  45.             Console.WriteLine ("El thread `{0}` se ha iniciado y espera en el semáforo.",
  46.                 numero
  47.             );
  48.             semaforo.WaitOne ();
  49.            
  50.             // Suma una cantidad de tiempo al intervalo anterior:
  51.             int intervalo = Interlocked.Add (ref _intervalo, 100);
  52.            
  53.             Console.WriteLine ("El thread `{0}` acaba de entrar al semáforo.",
  54.                 numero
  55.             );
  56.            
  57.             // Simula la ejecución de una tarea larga:
  58.             Thread.Sleep (1000 + intervalo);
  59.            
  60.             Console.WriteLine ("El thread `{0}` libera el semáforo.", numero );
  61.             Console.WriteLine ("Contador de threads en el semáforo: {0}",
  62.                 semaforo.Release()
  63.             );
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement