Coding Memo

ThreadPool (SetMinThreads, SetMaxThreads) 주의사항 본문

Language/C#

ThreadPool (SetMinThreads, SetMaxThreads) 주의사항

minttea25 2023. 5. 2. 14:33

Summary

SetMinThreads로 Worker Thread의 최소 수를 지정할 때는 SetMaxThreads로 최대 수도 함께 지정해주어야 한다.

(그 역도 마찬가지이다.)

그렇지 않으면 System의 default 값이 적용된다.


코드를 테스트하다가 우연히 알게 되었다. SetMaxThreads로 worker 쓰레드 수를 한정하고 초과 개수의 쓰레드를 돌려도 잘 돌아가는 현상을 보고 ‘뭐지…’ 하고 한참을 찾아보고 테스트 해보다가 해결했다.

 

using System;
using System.Threading;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.SetMinThreads(1, 1);
            ThreadPool.SetMaxThreads(5, 5);
            {
                ThreadPool.GetMinThreads(out var mn, out _);
                Console.WriteLine($"Min threads: {mn}");

                ThreadPool.GetMaxThreads(out var mx, out _);
                Console.WriteLine($"Max threads: {mx}");

                ThreadPool.GetAvailableThreads(out var av, out _);
                Console.WriteLine($"Available threads: {av}");
            }
        }
    }
}

Result:

Min threads: 1
Max threads: 5
Available threads: 5

 

위 코드에서 SetMinThreads()나 SetMaxThreads() 둘 중 하나만 실행 시켰을 때 다음과 같이 나온다.

Min threads: 6
Max threads: 32767
Available threads: 32767

적용이 안된 것을 알 수 있었다.

 

 

GPT에도 물어보니까 맞다고 한다.

In C#, if both the minimum and maximum number of threads in ThreadPool are not explicitly defined, neither is applied. Is it correct?
Yes, that is correct. If the minimum and maximum number of threads in the ThreadPool are not explicitly defined, the default values are used. The default minimum number of threads is equal to the number of processors on the computer, and the default maximum number of threads is equal to twice the number of processors. However, these values are not guaranteed and can vary depending on the environment the application is running on. It's always recommended to explicitly set the minimum and maximum number of threads in the ThreadPool for more predictable behavior.

References: