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);
}
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uVGhyZWFkaW5nOwoKbmFtZXNwYWNlIFJlY2V0YXMuQ1NoYXJwLkNhcDA0LlIwNDExCnsKICAgIHB1YmxpYyBzZWFsZWQgY2xhc3MgVXNvQWRkCiAgICB7CiAgICAgICAgLy8gVmFsb3IgZGUgZGF0byBjb21wYXJ0aWRvIGVudHJlIHRocmVhZHM6CiAgICAgICAgcHJpdmF0ZSBzdGF0aWMgaW50IHZhcmlhYmxlOwogICAgICAgIAogICAgICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBNYWluKCkKICAgICAgICB7CiAgICAgICAgICAgIC8vIENyZWFjacOzbiBkZSBkb3MgdGhyZWFkczoKICAgICAgICAgICAgVGhyZWFkIHQxID0gbmV3IFRocmVhZChTdW1hcik7CiAgICAgICAgICAgIFRocmVhZCB0MiA9IG5ldyBUaHJlYWQoU3VtYXIpOwogICAgICAgICAgICAKICAgICAgICAgICAgLy8gSW5pY2lvIGRlIGxhIGVqZWN1Y2nDs24gZGUgbG9zIGRvcyB0aHJlYWRzOgogICAgICAgICAgICB0MS5TdGFydCgpOwogICAgICAgICAgICB0Mi5TdGFydCgpOwogICAgICAgICAgICAKICAgICAgICAgICAgLy8gRXNwZXJhIHN1IGZpbmFsaXphY2nDs246CiAgICAgICAgICAgIHQxLkpvaW4oKTsKICAgICAgICAgICAgdDIuSm9pbigpOwogICAgICAgICAgICAKICAgICAgICAgICAgLy8gTXVlc3RyYSBlbCB2YWxvciBmaW5hbCBkZSBgdmFyaWFibGVgOgogICAgICAgICAgICBDb25zb2xlLldyaXRlTGluZSAoIlxuVmFsb3IgZGUgYHZhcmlhYmxlYDogezB9XG4iLCB2YXJpYWJsZS5Ub1N0cmluZygpKTsKICAgICAgICB9CiAgICAgICAgCiAgICAgICAgcHJpdmF0ZSBzdGF0aWMgdm9pZCBTdW1hcigpCiAgICAgICAgewogICAgICAgICAgICAvLyBTdW1hIDIgYSBgdmFyaWFibGVgOgogICAgICAgICAgICBJbnRlcmxvY2tlZC5BZGQgKHJlZiB2YXJpYWJsZSwgMik7CiAgICAgICAgfQogICAgfQp9