using System; using System.Diagnostics; using System.Threading; namespace Recetas.Multithreading.Cap01.R0106 { public class ManejadorThread { private bool detenido = false; public void Detener() { detenido = true; } public void ContarNumeros() { long contador = 0; while (!detenido) { ++contador; } Console.WriteLine ("\nEl thread `{0}` con prioridad {1,11} tiene un contador de {2,13}.", Thread.CurrentThread.Name, Thread.CurrentThread.Priority.ToString(), contador.ToString ("N0") ); } } public sealed class EjecucionThreadEnCore { public static void EjecutarThreads () { ManejadorThread mt = new ManejadorThread(); // Crea dos instancias de Thread y les // asigna un nombre identificativo: Thread t1 = new Thread (mt.ContarNumeros); t1.Name = "Thread no. 1"; Thread t2 = new Thread (mt.ContarNumeros); t2.Name = "Thread no. 2"; // Establece el nivel de prioridad: t1.Priority = ThreadPriority.Highest; t2.Priority = ThreadPriority.Lowest; // Inicio de la ejecución de los threads: t1.Start (); t2.Start (); // Detiene el Thread actual por 2 segundos: Thread.Sleep (TimeSpan.FromSeconds (2)); mt.Detener(); } public static void Main() { Console.WriteLine ("\nPrioridad del thread Main: {0}", Thread.CurrentThread.Priority ); Console.WriteLine ("Ejecución sobre todos los núcleos (cores) disponibles..."); EjecutarThreads(); // Detiene al thread Main por 2 segundos: Thread.Sleep (TimeSpan.FromSeconds (3)); Console.WriteLine ("\nEjecución sobre un único núcleo (core)..."); Process.GetCurrentProcess().ProcessorAffinity = new IntPtr (1); EjecutarThreads(); } } }