/// <summary> /// A default static constructor that initializes the pool threads. /// </summary> static SmartThreadPool() { //create a scheduler for threads created outside the computation system. //By default this is a heap scheduller since there can be much more threads, //thus heap sort is more efficient. artificialThreadScheduler = Configuration.ArtificialThreadScheduler; uint physicalProcessors = Unsafe.GetPhysicalCores(); //the idea here is {core_count} * 2 the rest should be spawned as fibers. ISchedulableThread[] threads = new ISchedulableThread[physicalProcessors * 2]; for (int i = 0; i < threads.Length; i++) { threads[i] = new SmartThread(true, -1); threads[i].SchedulableIndex = i; if (Configuration.SmartThreadPoolPreLoadThreads) { threads[i].Start(); } } //Load the default thread scheduler. threadScheduler = Configuration.SmartPoolScheduler; threadScheduler.Create(threads); }
/// <summary> /// Tries to steal workload from other heavy loaded threads. /// </summary> /// <returns>a boolan flag indicating the steal success or failure.</returns> internal bool TryStealWork() { //1. Ask the pool for a thread with the worst stats. //2. Access it's internal queue by calling count and then doing Dequeue // Here we eith hold a lock or we dont lock at all and handle all queue empty exception. SmartThread threadToSteal = (SmartThread)SmartThreadPool.GetThreadToSteal(isInitializedInPool); //This code is needed as ThreadPool might tell us that in some sittuations that we can steal //work from ourselvs for e.g if other thread will join or we will fork ourselfs and the operations //is running. if (threadToSteal.id != this.id) { //perform a steal but only if the window is grater then 1 this means that we will //try to snach the item when no one is asking for it, if we fail we still do it in lock free //fashion but we may spin. bool result = TryStealFromQueue(threadToSteal.scheduler, stealCondition); //update the stats. if (result) { SmartThreadPool.Reschedule(isInitializedInPool, threadToSteal, SchedulerAction.Dequeue); } return(result); } return(false); }
public static int GetThreadLoad() { SmartThread thread = (SmartThread)threadScheduler.GetBestThread(); return(thread.scheduler.UnsafeCount); }
/// <summary> /// Removes the given thread that not orginated in a thread pool from the artificial scheduler. /// </summary> /// <param name="thread">SmartThread</param> internal static void RemoveFromArtificialScheduler(SmartThread thread) { artificialThreadScheduler.Remove(thread); }
/// <summary> /// Inserts a thread that not orginated in a thread pool to the artificial scheduler, /// in order to enable fair work scheduling and work stealing. /// </summary> /// <param name="thread">SmartThread.</param> internal static void InsertToArtificialScheduler(SmartThread thread) { artificialThreadScheduler.Add(thread); }