Thread Pool

  • 3 Replies
  • 248 Views
*

frankinstien

  • Starship Trooper
  • *******
  • 374
    • Knowledgeable Machines
Thread Pool
« on: February 05, 2021, 11:17:33 pm »
I was in need of a very simple thread pool and not use Microsoft's ThreadPool library because I wanted control over priority and not have to deal with the scheduling issues with Microsoft's library: Below is the code for anyone to use if you program in .NET:

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;


namespace xThreadPool
{
    public class Pool
    {
        protected List<AccessObject>[] threadsOne;       

        private int poolSize;
        protected object threadLock = new object();       

        public Pool(int size)
        {           
            threadsOne = new List<AccessObject>[4];           
             poolSize = size;
            for(byte x = 0;x<4;x++)
                BuildPooledThreads(x);
           
        }
       

        /// <summary>
        /// This method creates a new list to add new threads to a thread bank
        /// from the array list indexed by z.
        /// </summary>
        /// <param name="z"></param>
        protected void BuildPooledThreads(byte z)
        {
                         
            threadsOne[z] = new List<AccessObject>();
            for (int x = 0; x < poolSize; x++)
            {
                var access = new AccessObject(x);                   
                   
                threadsOne[z].Add(access);
            }       
        }       

        /// <summary>
        /// This method pushes the delegate onto a thread from a list of available threads.
        /// </summary>
        /// <param name="method"></param>
        /// <param name="setPriority"></param>
        public void Run(Action method, ThreadPriority setPriority = ThreadPriority.AboveNormal)
        {
            AccessObject aThread = default;
            byte z = 0;
            lock (threadLock)
            {
                do
                {

                    aThread = threadsOne[z].Where(x => x.StoredThread.ThreadState == ThreadState.Suspended).FirstOrDefault();
                    if (aThread == null)
                    {
                        if (z < 3)
                            z++;
                        else
                            z = 0;
                    }

                } while (aThread == null);
                aThread.MethodToStart = method;
                aThread.StoredThread.Priority = setPriority;
                aThread.StoredThread.Resume();
            }
        }
    }

    /// <summary>
    /// This class is used to control a thread and exection of an applied delegate
    /// </summary>
    public class AccessObject : IDisposable
    {
        public int ID { set; get; }
        public Action MethodToStart { set; get; }       
        public bool StopThread { set; get; }
        public Thread StoredThread { private set; get; }

        public AccessObject(int identifier)
        {
            ID = identifier;
            StopThread = false;
            ThreadStart aStart = new ThreadStart(ExecuteMethod);
            StoredThread = new Thread(aStart);
            StoredThread.Start();
        }

        /// <summary>
        /// This is the executing method for the applied delegate MethodToStart
        /// </summary>
        public void ExecuteMethod()
        {
            do
            {
                Thread.CurrentThread.Suspend();
                MethodToStart();
            } while (!StopThread);
        }

        public void Dispose()
        {
            StopThread = true;
            if (StoredThread != null)
                StoredThread.Abort();
        }
    }
}


*

yotamarker

  • Trusty Member
  • *********
  • Terminator
  • *
  • 889
    • battle programming
Re: Thread Pool
« Reply #1 on: February 07, 2021, 02:52:51 am »
this is somewhat similar to coroutins

*

infurl

  • Administrator
  • **********
  • Millennium Man
  • *
  • 1094
  • Humans will disappoint you.
    • Home Page
Re: Thread Pool
« Reply #2 on: February 07, 2021, 03:13:34 am »
this is somewhat similar to coroutines

I agree, the difference being that threads are preemptive and coroutines are co-operative. I've been thinking about this and wondering why you would need to attempt to schedule threads yourself. It is more efficient to let the operating system do it and a thread implementation would normally provide mechanisms such as semaphores for regulating their behaviour.

*

frankinstien

  • Starship Trooper
  • *******
  • 374
    • Knowledgeable Machines
Re: Thread Pool
« Reply #3 on: February 07, 2021, 07:53:06 pm »
I agree, the difference being that threads are preemptive and coroutines are co-operative. I've been thinking about this and wondering why you would need to attempt to schedule threads yourself. It is more efficient to let the operating system do it and a thread implementation would normally provide mechanisms such as semaphores for regulating their behaviour.

The implementation of the mutexes and/or semaphores are implemented at the method or function level. When you use Task.Run or the ThreadPool library setting priority of the thread has to happen at the method or function level which is what I don't want and I want the choice of the threads to be foreground threads or background threads. When you set the priority to normal or above there is better distribution of the threads across all cores, which is what I want. While everyone says you can't preserve a thread under .NET, well guess what? The code I listed does exactly that, and because the threads are created at the start of the application it accelerates the use of threads. Since creating and starting threads can take a very long time relatively speaking. So when the threads are created they are started as well, then suspended only to be retrieved when needed and the thread is resumed which executes the applied or pushed method and then suspended after the method(Thread) finishes.

 


SwarmFarm agricultural robots
by infurl (Robotics News)
February 28, 2021, 12:48:38 am
Microsoft Patent To Construct Chatbots of Dead People Approved
by MikeB (AI News )
February 18, 2021, 06:18:35 am
New challenge: Online Turing test
by Denis ROBERT (AI News )
February 15, 2021, 02:53:24 pm
Loebner Prize 2021
by Denis ROBERT (AI News )
February 10, 2021, 02:20:25 pm
Smart Matter
by infurl (AI News )
February 09, 2021, 05:09:31 am

Users Online

80 Guests, 0 Users

Most Online Today: 157. Most Online Ever: 2369 (November 21, 2020, 04:08:13 pm)

Articles