using System;
using System.Threading;
namespace Recetas.CSharp.Cap04.R0411
{
public sealed class UsoIncrementDecrement
{
// Valor de dato compartido entre threads:
private static int variable = 0;
public static void Main()
{
// Creación de dos threads:
Thread t1 = new Thread(IncrementarDecrementar);
Thread t2 = new Thread(IncrementarDecrementar);
// 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 IncrementarDecrementar()
{
// Incrementa y decrementa el valor de `variable`:
Interlocked.Increment(ref variable);
Interlocked.Decrement(ref variable);
Interlocked.Decrement(ref variable);
}
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uVGhyZWFkaW5nOwoKbmFtZXNwYWNlIFJlY2V0YXMuQ1NoYXJwLkNhcDA0LlIwNDExCnsKICAgIHB1YmxpYyBzZWFsZWQgY2xhc3MgVXNvSW5jcmVtZW50RGVjcmVtZW50CiAgICB7CiAgICAgICAgLy8gVmFsb3IgZGUgZGF0byBjb21wYXJ0aWRvIGVudHJlIHRocmVhZHM6CiAgICAgICAgcHJpdmF0ZSBzdGF0aWMgaW50IHZhcmlhYmxlID0gMDsKICAgICAgICAKICAgICAgICBwdWJsaWMgc3RhdGljIHZvaWQgTWFpbigpCiAgICAgICAgewogICAgICAgICAgICAvLyBDcmVhY2nDs24gZGUgZG9zIHRocmVhZHM6CiAgICAgICAgICAgIFRocmVhZCB0MSA9IG5ldyBUaHJlYWQoSW5jcmVtZW50YXJEZWNyZW1lbnRhcik7CiAgICAgICAgICAgIFRocmVhZCB0MiA9IG5ldyBUaHJlYWQoSW5jcmVtZW50YXJEZWNyZW1lbnRhcik7CiAgICAgICAgICAgIAogICAgICAgICAgICAvLyBJbmljaW8gZGUgbGEgZWplY3VjacOzbiBkZSBsb3MgZG9zIHRocmVhZHM6CiAgICAgICAgICAgIHQxLlN0YXJ0KCk7CiAgICAgICAgICAgIHQyLlN0YXJ0KCk7CiAgICAgICAgICAgIAogICAgICAgICAgICAvLyBFc3BlcmEgc3UgZmluYWxpemFjacOzbjoKICAgICAgICAgICAgdDEuSm9pbigpOwogICAgICAgICAgICB0Mi5Kb2luKCk7CiAgICAgICAgICAgIAogICAgICAgICAgICAvLyBNdWVzdHJhIGVsIHZhbG9yIGZpbmFsIGRlIGB2YXJpYWJsZWA6CiAgICAgICAgICAgIENvbnNvbGUuV3JpdGVMaW5lICgiXG5WYWxvciBkZSBgdmFyaWFibGVgOiB7MH1cbiIsIHZhcmlhYmxlLlRvU3RyaW5nKCkpOwogICAgICAgIH0KICAgICAgICAKICAgICAgICBwcml2YXRlIHN0YXRpYyB2b2lkIEluY3JlbWVudGFyRGVjcmVtZW50YXIoKQogICAgICAgIHsKICAgICAgICAgICAgLy8gSW5jcmVtZW50YSB5IGRlY3JlbWVudGEgZWwgdmFsb3IgZGUgYHZhcmlhYmxlYDoKICAgICAgICAgICAgSW50ZXJsb2NrZWQuSW5jcmVtZW50KHJlZiB2YXJpYWJsZSk7CiAgICAgICAgICAgIEludGVybG9ja2VkLkRlY3JlbWVudChyZWYgdmFyaWFibGUpOwogICAgICAgICAgICBJbnRlcmxvY2tlZC5EZWNyZW1lbnQocmVmIHZhcmlhYmxlKTsKICAgICAgICB9CiAgICB9Cn0=