Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created August 7, 2014 09:57
Show Gist options
  • Save Fhernd/34e64a131b5d4bda8f0e to your computer and use it in GitHub Desktop.
Save Fhernd/34e64a131b5d4bda8f0e to your computer and use it in GitHub Desktop.
Demostración del uso del método Interlocked.Add en C#.
using System;
using System.Threading;
namespace Recetas.CSharp.Cap04.R0411
{
public sealed class UsoAdd
{
// Valor de dato compartido entre threads:
private static int variable;
public static void Main()
{
// Creación de dos threads:
Thread t1 = new Thread(Sumar);
Thread t2 = new Thread(Sumar);
// Inicio de la ejecución de los dos threads:
t1.Start();
t2.Start();
// Espera su finalización:
t1.Join();
t2.Join();
// Muestra el valor final de `variable`:
Console.WriteLine ("\nValor de `variable`: {0}\n", variable.ToString());
}
private static void Sumar()
{
// Suma 2 a `variable`:
Interlocked.Add (ref variable, 2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment