Created
July 24, 2014 00:27
-
-
Save Fhernd/3f14925eeb61695bb13e to your computer and use it in GitHub Desktop.
Demostración del uso de la clase Semaphore.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
namespace Recetas.CSharp.Cap04.R0410 | |
{ | |
public sealed class UsoSincronizacionSemaphore | |
{ | |
// Representa una instancia de Semaphore: | |
private static Semaphore semaforo; | |
// Intervalo de orden de la salida: | |
private static int _intervalo; | |
public static void Main() | |
{ | |
Console.Title = "Uso Sincronización Semáforo"; | |
Console.WriteLine (); | |
// Crea una instancia de Semaphore> | |
semaforo = new Semaphore(0, 3); | |
// Crea hasta 5 threads: | |
for (int i = 1; i <= 5; ++i) | |
{ | |
Thread t = new | |
Thread(new ParameterizedThreadStart (Tarea)); | |
t.Start (i); | |
} | |
// Suspensión por 0.5 segundos para dejar que todos los | |
// threads entren en el semáforo: | |
Thread.Sleep (500); | |
// Completa el semáforo (atención de todos los threads): | |
Console.WriteLine ("Invocación de semaforo.Release(3)."); | |
semaforo.Release(3); | |
Console.WriteLine ("\n`Main` ha finalizado.\n"); | |
} | |
private static void Tarea(object numero) | |
{ | |
// Cada thread solicita el paso al objeto Semaphore: | |
Console.WriteLine ("El thread `{0}` se ha iniciado y espera en el semáforo.", | |
numero | |
); | |
semaforo.WaitOne (); | |
// Suma una cantidad de tiempo al intervalo anterior: | |
int intervalo = Interlocked.Add (ref _intervalo, 100); | |
Console.WriteLine ("El thread `{0}` acaba de entrar al semáforo.", | |
numero | |
); | |
// Simula la ejecución de una tarea larga: | |
Thread.Sleep (1000 + intervalo); | |
Console.WriteLine ("El thread `{0}` libera el semáforo.", numero ); | |
Console.WriteLine ("Contador de threads en el semáforo: {0}", | |
semaforo.Release() | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment