Thread Pool

  • 3 Replies
  • 2771 Views
*

frankinstien

  • Replicant
  • ********
  • 642
    • 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
  • **********
  • Millennium Man
  • *
  • 1003
  • battle programmer
    • battle programming
Re: Thread Pool
« Reply #1 on: February 07, 2021, 02:52:51 am »
this is somewhat similar to coroutins

*

infurl

  • Administrator
  • ***********
  • Eve
  • *
  • 1365
  • 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

  • Replicant
  • ********
  • 642
    • 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.

 


OpenAI Speech-to-Speech Reasoning Demo
by ivan.moony (AI News )
March 28, 2024, 01:31:53 pm
Say good-bye to GPUs...
by MikeB (AI News )
March 23, 2024, 09:23:52 am
Google Bard report
by ivan.moony (AI News )
February 14, 2024, 04:42:23 pm
Elon Musk's xAI Grok Chatbot
by MikeB (AI News )
December 11, 2023, 06:26:33 am
Nvidia Hype
by 8pla.net (AI News )
December 06, 2023, 10:04:52 pm
How will the OpenAI CEO being Fired affect ChatGPT?
by 8pla.net (AI News )
December 06, 2023, 09:54:25 pm
Independent AI sovereignties
by WriterOfMinds (AI News )
November 08, 2023, 04:51:21 am
LLaMA2 Meta's chatbot released
by 8pla.net (AI News )
October 18, 2023, 11:41:21 pm

Users Online

257 Guests, 0 Users

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

Articles