Thread Pool

  • 3 Replies
  • 3511 Views
*

frankinstien

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

 


Requirements for functional equivalence to conscious processing?
by DaltonG (General AI Discussion)
November 19, 2024, 11:56:05 am
Will LLMs ever learn what is ... is?
by HS (Future of AI)
November 10, 2024, 06:28:10 pm
Who's the AI?
by frankinstien (Future of AI)
November 04, 2024, 05:45:05 am
Project Acuitas
by WriterOfMinds (General Project Discussion)
October 27, 2024, 09:17:10 pm
Ai improving AI
by infurl (AI Programming)
October 19, 2024, 03:43:29 am
Atronach's Eye
by WriterOfMinds (Home Made Robots)
October 13, 2024, 09:52:42 pm
Running local AI models
by spydaz (AI Programming)
October 07, 2024, 09:00:53 am
Hi IM BAA---AAACK!!
by MagnusWootton (Home Made Robots)
September 16, 2024, 09:49:10 pm
LLaMA2 Meta's chatbot released
by spydaz (AI News )
August 24, 2024, 02:58:36 pm
ollama and llama3
by spydaz (AI News )
August 24, 2024, 02:55:13 pm
AI controlled F-16, for real!
by frankinstien (AI News )
June 15, 2024, 05:40:28 am
Open AI GPT-4o - audio, vision, text combined reasoning
by MikeB (AI News )
May 14, 2024, 05:46:48 am
OpenAI Speech-to-Speech Reasoning Demo
by MikeB (AI News )
March 31, 2024, 01:00: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

Users Online

498 Guests, 0 Users

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

Articles