Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 16, 2015 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/4e04c014f703503e0d52 to your computer and use it in GitHub Desktop.
Save Fhernd/4e04c014f703503e0d52 to your computer and use it in GitHub Desktop.
Uso de la estructura `SpinWait`.
// OrtizOL - xCSw - http://ortizol.blogspot.com
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Receta.Multithreading.R0208
{
public class UsoSpinWait
{
public static void Main()
{
Console.WriteLine(Environment.NewLine);
bool valorCentinela = false;
int numeroCedes = 0;
// Contamos con SpinWait mientras que la variable
// lógica centinela se hace igual a verdadero:
Task t1 = Task.Factory.StartNew(() =>
{
SpinWait sw = new SpinWait();
while (!valorCentinela)
{
// Determina si se cedió el control al procesador en lugar de
// de simple ~girar (spin):
if (sw.NextSpinWillYield)
{
++numeroCedes;
}
sw.SpinOnce();
}
Console.WriteLine("Número de llamadas de SpinWait: {0} - Cedido {1} veces.", sw.Count, numeroCedes);
}
);
// En otro thread cambiamos el valor de la variable centinela:
Task t2 = Task.Factory.StartNew(() =>
{
Thread.Sleep (200);
valorCentinela = true;
}
);
// Espera hasta que todos los threads finalicen:
Task.WaitAll(t1, t2);
Console.WriteLine(Environment.NewLine);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment