locked
ThreadPool RRS feed

  • Question

  • User2011562055 posted

    Hi All,

    Am implementing the threadpool concept and have doutbt in threads being created.

    Boolean bdone= ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadExecution));

    I've read that when the following line is being executed, 25 threads will be created. But i want only 5 threads to run at the same time and more than 5 requests want it to be queued and the same 5 threads should be reused. In order to do this i tried to use semaphores like below.

     private void ThreadExecution(Object test)
            {
                 Semaphore maxThreads = new Semaphore(5,5);
                    while (maxThreads.WaitOne())
                    {
                          MY CODE
                         maxThreads.Release();
                     }
            }

    Initially i gave (1,1) in semaphores and only one thread was created and it did only one task, and (5,5) created one thread and it used for all the times.

    Is ter anything wrong in wat i did or any other way of doin other than semaphores. And mainly wat abt the remaining 20 threads in threadpool? its a waste of CPU right. Can i create only 5?

    Thanks in advance.

     

    Friday, May 14, 2010 1:33 PM

Answers

  • User1154043639 posted

    What do you think, if you revert it after creating threads

            public static void Execute()
            {
                ThreadPool.SetMaxThreads(5, 5);
                ///
                /// Your code...
                ///
                ThreadPool.SetMaxThreads(25, 25);
            }


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 17, 2010 5:40 AM

All replies

  • User1154043639 posted

    Just a thought,

    Cant we use: ThreadPool.SetMaxThreads(5, 5); I had a play with 10 threads, it seems working for me

    Original example is taken from: MSDN : How to create thread pool

    Modfied example: using ThreadPool.SetMaxThreads(5,5)

    using System;
    using System.Threading;
    
    namespace Fabonacci
    {
        public class Fibonacci
        {
            public Fibonacci(int n, ManualResetEvent doneEvent)
            {
                _n = n;
                _doneEvent = doneEvent;
            }
            public void ThreadPoolCallback(Object threadContext)
            {
                int threadIndex = (int)threadContext;
                Console.WriteLine("thread {0} started...", threadIndex);
                _fibOfN = Calculate(_n);
                Console.WriteLine("thread {0} result calculated...", threadIndex);
                _doneEvent.Set();
            }
            public int Calculate(int n)
            {
                if (n <= 1)
                    return n;
                Thread.Sleep(2);
                return Calculate(n - 1) + Calculate(n - 2);
            }
            public int N { get { return _n; } }
            private int _n;
            public int FibOfN { get { return _fibOfN; } }
            private int _fibOfN;
            private ManualResetEvent _doneEvent;
        }
        public class ThreadPoolExample
        {
            public static void Execute()
            {
                ThreadPool.SetMaxThreads(5, 5);
                const int FibonacciCalculations = 10;
                ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
                Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
                Random r = new Random();
                Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
                for (int i = 0; i < FibonacciCalculations; i++)
                {
                    doneEvents[i] = new ManualResetEvent(false);
                    Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
                    fibArray[i] = f;
                    ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
                }
                WaitHandle.WaitAll(doneEvents);
                Console.WriteLine("All calculations are complete.");
                for (int i = 0; i < FibonacciCalculations; i++)
                {
                    Fibonacci f = fibArray[i];
                    Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
                }
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                ThreadPoolExample.Execute();
            }
        }
    }
    


    Friday, May 14, 2010 5:16 PM
  • User2011562055 posted

    Hi,

    If i use Threadpool.SetMaxThreads(5,5) i understand that it'll set the max no of threads in the threadpool to 5. As the entire OS uses the threadpool, limiting it to 5 could cause problems right? So i want to restrict it to 5 in just my application. So i want to use something like a counter, but just dont know where to use the counter. 

    Thanks for ur reply but can u help me on this now.

     

    Sunday, May 16, 2010 9:42 AM
  • User1154043639 posted

    What do you think, if you revert it after creating threads

            public static void Execute()
            {
                ThreadPool.SetMaxThreads(5, 5);
                ///
                /// Your code...
                ///
                ThreadPool.SetMaxThreads(25, 25);
            }


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 17, 2010 5:40 AM
  • User2011562055 posted

    Hey wow...excellent idea...thanks for it...:) 

    Wednesday, May 19, 2010 2:37 AM
  • User2011562055 posted

    Hey Charith,

    Just one more doubt. This 25 per thread pool is processor specific right. Like if its a core2duo it'll b 50 threads in the pool. So can i make that statement generic so tat acc to the processor it'll choose the no of threads. 

    Wednesday, May 19, 2010 3:08 AM
  • User1154043639 posted

    ThreadPool.SetMaxThreads(25, 25); means

    1. 25 worker threads
    2. 25 I/O threads

    So callig ThreadPool.SetMaxThreads(25, 25);  will create 25 worker threads and 25 I/O threads anyway. (50)

    Addressing your question, as far as I know answer is NO using ThreadPool [ICorThreadpool Interface],

    PS: I am not 100% confidence on my knowlege of processor architecture but please do read more about process architecture if I am wrong please let me know.

    In threory:

    1. ThreadPool.SetMaxTreads(n,n) will create n number of threads per processor 1 core 2n
    2. So in theory, dual core ( 2 processor ) 2n * 2
    3. Core 2 duo ( 4 processors ) 2n * 4

    Thats what we can prove using theory,

    in C# and using WMI and System.Management we can find Available processors and Number Of Cores for 32 bit processor

        public class XManagement
        {
            public static List<Processor> GetProcessors()
            {
                ManagementClass c = new ManagementClass("Win32_Processor");
                List<Processor> processors = new List<Processor>();
                foreach (ManagementObject p in c.GetInstances())
                    processors.Add(new Processor() { Name = p["Name"].ToString(), NumberOfCores = int.Parse((p["NumberOfCores"]).ToString()) });
                return processors;
            }
        }
        public class Processor
        {
            public string Name;
            public int NumberOfCores;
        }


    Please refer ICorThreadpool Interface interface members

    Header file: MSCorEE.h

    Useful Links:

    1. Using WMI
    2. Win32_Processor
    3. WMI.Net Overview
    4. WMI .NET Code Directory

    Thanks

    Thursday, May 20, 2010 8:48 AM