Created
August 1, 2014 01:03
-
-
Save Fhernd/19dd26572ce85a9fc94e to your computer and use it in GitHub Desktop.
Demostración de la sincronización de contadores.
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.Multithreading.Cap04.R0109 | |
{ | |
public sealed class PruebaContador | |
{ | |
public static void Main() | |
{ | |
Console.Title = "No-Sincronizado vs Sincronizado"; | |
Console.WriteLine (); | |
Console.WriteLine ("=== Contador con Errores ==="); | |
// Crea un ContadorBasico: | |
ContadorBasico c = new ContadorBasico(); | |
// Crea 3 threads: | |
Thread t1 = new Thread(() => ProbarContador(c)); | |
Thread t2 = new Thread(() => ProbarContador(c)); | |
Thread t3 = new Thread(() => ProbarContador(c)); | |
// Inicio de ejecución de los threads: | |
t1.Start(); | |
t2.Start(); | |
t3.Start(); | |
// Espera a que finalicen: | |
t1.Join(); | |
t2.Join(); | |
t3.Join(); | |
Console.WriteLine ("\nCuenta total (no sincronizado): {0}\n\n", c.Cuenta.ToString()); | |
Console.WriteLine ("=== Contador con Sincronización ==="); | |
// Crea una instancia de ContadorSincronizado: | |
ContadorSincronizado cs = new ContadorSincronizado(); | |
t1 = new Thread(() => ProbarContador(cs)); | |
t2 = new Thread(() => ProbarContador(cs)); | |
t3 = new Thread(() => ProbarContador(cs)); | |
// Inicio de ejecución de los threads: | |
t1.Start(); | |
t2.Start(); | |
t3.Start(); | |
// Espera a que finalicen: | |
t1.Join(); | |
t2.Join(); | |
t3.Join(); | |
Console.WriteLine ("\nCuenta total (sincronizado): {0}\n\n", cs.Cuenta.ToString()); | |
} | |
private static void ProbarContador(ContadorAbstracto c) | |
{ | |
for (int i = 0; i < 10000; ++i) | |
{ | |
c.Incrementar(); | |
c.Decrementar(); | |
} | |
} | |
} | |
public abstract class ContadorAbstracto | |
{ | |
public abstract void Incrementar(); | |
public abstract void Decrementar(); | |
} | |
// Clase que representa un contador sin sincronización: | |
public class ContadorBasico : ContadorAbstracto | |
{ | |
public int Cuenta | |
{ | |
get; | |
private set; | |
} | |
public override void Incrementar() | |
{ | |
++Cuenta; | |
} | |
public override void Decrementar() | |
{ | |
--Cuenta; | |
} | |
} | |
// Clase que representa un contador con sincronización: | |
public class ContadorSincronizado : ContadorAbstracto | |
{ | |
private readonly Object bloqueo = new Object(); | |
public int Cuenta | |
{ | |
get; | |
private set; | |
} | |
public override void Incrementar() | |
{ | |
lock (bloqueo) | |
{ | |
++Cuenta; | |
} | |
} | |
public override void Decrementar() | |
{ | |
lock (bloqueo) | |
{ | |
--Cuenta; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment