Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help understanding .net ThreadPool

I am trying to understand what ThreadPool does, I have this .NET example:

class Program
{
    static void Main()
    {
        int c = 2;

        // Use AutoResetEvent for thread management

        AutoResetEvent[] arr = new AutoResetEvent[50];

        for (int i = 0; i < arr.Length; ++i)
        {
            arr[i] = new AutoResetEvent(false);
        }

        // Set the number of minimum threads
        ThreadPool.SetMinThreads(c, 4);

        // Enqueue 50 work items that run the code in this delegate function
        for (int i = 0; i < arr.Length; i++)
        {
            ThreadPool.QueueUserWorkItem(delegate(object o)
            {
                Thread.Sleep(100);
                arr[(int)o].Set(); // Signals completion

            }, i);
        }

        // Wait for all tasks to complete
        WaitHandle.WaitAll(arr);
    }
}

Does this run 50 "tasks", in groups of 2 (int c) until they all finish? Or I am not understanding what it really does.

like image 903
Meredith Avatar asked May 05 '26 20:05

Meredith


1 Answers

If you've got a bit of time, I would really recommend this read:

http://www.albahari.com/threading/

It's an excellent read that lays the foundation and works it's way from basic threading to parallel programming. I'd recommend you to have a basic grasp of the first two chapters before trying to modify threadpool code! :)

like image 115
Joe Avatar answered May 08 '26 13:05

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!