Created
July 23, 2014 17:51
-
-
Save Fhernd/bb6d51bf72cecbe795c4 to your computer and use it in GitHub Desktop.
Uso de Mutex para sincronización de un recurso compartido: la consola.
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.R0409 | |
{ | |
public sealed class RecursoCompartidoConsola | |
{ | |
// Determina el estado de ejecución de un thread: | |
private static bool terminarThread = false; | |
// Muestra mensajes de información acerca del estado | |
// de ejecución de un thread: | |
private static void Rastrear(string mensaje) | |
{ | |
Console.WriteLine ("[{0,3}] - {1} : {2}", | |
Thread.CurrentThread.ManagedThreadId, | |
DateTime.Now.ToString("HH:mm:ss.ffff"), | |
mensaje | |
); | |
} | |
// Método a encapsular por diferentes threads y que | |
// contiene una región crítica protegida por un | |
// objeto Mutex: | |
private static void MostrarMensajeEnConsola() | |
{ | |
// Se apropia de un instancia Mutex con nombre | |
// 'EjemploMutex': | |
using (Mutex mutex = new Mutex (false, "EjemploMutex")) | |
{ | |
Rastrear("Inicio ejecución de thread."); | |
while (!terminarThread) | |
{ | |
// Apoderamiento del mutex: | |
mutex.WaitOne(); | |
Rastrear("Apoderamiento del Mutex."); | |
Thread.Sleep(1000); | |
Rastrear ("Liberación del Mutex."); | |
mutex.ReleaseMutex(); | |
// Pausa para dar la oportunidad de que otro | |
// thread se apodere del mutex: | |
Thread.Sleep (100); | |
} | |
Rastrear ("A punto de finalizar un thread."); | |
} | |
} | |
public static void Main() | |
{ | |
Console.Title = "Demostración uso de Sincronización con Mutex"; | |
Console.WriteLine (); | |
// Creación de una instancia de Mutex llamada `EjemploMutex`: | |
using (Mutex mutex = new Mutex (false, "EjemploMutex")) | |
{ | |
Rastrear ("Inicio de ejecución de threads. Presione Enter para finalizar."); | |
// Creación de 3 threads: | |
Thread t1 = new Thread (MostrarMensajeEnConsola); | |
Thread t2 = new Thread (MostrarMensajeEnConsola); | |
Thread t3 = new Thread (MostrarMensajeEnConsola); | |
t1.Start(); | |
t2.Start(); | |
t3.Start(); | |
Console.ReadLine (); | |
// Finaliza los threads asociados con el método `MostrarMensajeEnConsola`, | |
// y espera a que se completan antes de deshechar la instancia Mutex: | |
terminarThread = true; | |
t1.Join(5000); | |
t2.Join(5000); | |
t3.Join(5000); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment