Created
July 16, 2015 15:07
-
-
Save Fhernd/4e04c014f703503e0d52 to your computer and use it in GitHub Desktop.
Uso de la estructura `SpinWait`.
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
// 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