Programing

스레드 대 스레드 풀

crosscheck 2020. 6. 30. 20:42
반응형

스레드 대 스레드 풀


새 스레드를 사용하는 것과 스레드 풀의 스레드를 사용하는 것의 차이점은 무엇입니까? 어떤 성능 이점이 있으며, 명시 적으로 만든 스레드가 아닌 풀의 스레드를 사용해야하는 이유는 무엇입니까? 나는 여기서 .NET을 특별히 생각하고 있지만 일반적인 예는 좋습니다.


스레드 풀은 다음과 같이 빈번하고 비교적 짧은 작업에 이점을 제공합니다.

  • 새 스레드를 작성하는 대신 이미 작성된 스레드 재사용 (고가의 프로세스)
  • 새로운 작업 항목에 대한 요청이 급증 할 때 스레드 생성 속도 조절 (이것은 .NET 3.5에만 해당됨)

    • 100 개의 스레드 풀 작업을 대기열에 넣는 경우 이러한 요청을 처리하기 위해 이미 생성 된 수만큼의 스레드 만 사용합니다 (예 : 10). 스레드 풀은 자주 확인하고 (3.5 SP1에서 500ms마다 믿습니다) 대기중인 작업이있는 경우 하나의 새 스레드를 만듭니다. 작업이 빠르면 새 스레드 수가 적고 짧은 작업에 10 개 정도의 스레드를 재사용하면 100 개의 스레드를 미리 만드는 것보다 빠릅니다.

    • 워크로드에 지속적으로 많은 수의 스레드 풀 요청이 들어오는 경우, 스레드 풀은 위 프로세스에 의해 풀에 더 많은 스레드를 작성하여 요청을 처리하는 데 사용할 수있는 스레드 수가 더 많아 지므로 워크로드에 맞게 조정됩니다.

    • 스레드 풀이 후드 아래에서 작동하는 방법에 대한 자세한 내용은 여기확인하십시오.

작업이 비교적 오래 실행되는 경우 (아마도 1-2 초 정도이지만 특정 상황에 따라 다름) 새 스레드를 직접 만드는 것이 더 적합합니다.

@Krzysztof-스레드 풀 스레드는 기본 스레드가 끝나면 중지되는 백그라운드 스레드입니다. 수동으로 생성 된 스레드는 기본적으로 포 그라운드이지만 (메인 스레드가 종료 된 후에도 계속 실행 됨) 시작을 호출하기 전에 백그라운드로 설정할 수 있습니다.


.NET 관리 스레드 풀 :-

  • 현재 워크로드 및 사용 가능한 하드웨어를 기반으로 자체 크기 조정
  • 작업자 스레드 완료 포트 스레드 (IO를 서비스하는 데 특별히 사용됨)를 포함합니다.
  • 비교적 짧은 수명의 수많은 작업에 최적화

장기 실행 작업에 더 적합한 다른 스레드 풀 구현이 있습니다.

특히 스레드 풀을 사용하여 앱이 너무 많은 스레드 를 만들지 못하게합니다 . 스레드 풀의 가장 중요한 기능은 작업 대기열입니다. 즉, 일단 시스템이 충분히 사용 중이면 스레드 풀은 더 많은 스레드를 즉시 생성하지 않고 요청을 대기시킵니다.

따라서 작은 수의 스레드를 만들면 직접 만들 수 있습니다. 얼마나 많은 스레드가 생성되는지 (예 : 들어오는 IO에 대한 응답으로 생성 된) 선행 작업을 결정할 수없고 작업이 오래 지속되는 경우 스레드 풀을 사용하십시오. 몇 개를 알지 못하지만 그들의 작업이 오래 실행되는 경우 플랫폼에 도움이되는 것은 없지만 적합한 스레드 풀 구현을 찾을 수 있습니다.


또한

new Thread().Start()

프로그램을 닫아도 죽지 않는 포 그라운드 스레드를 생성합니다. ThreadPool 스레드는 앱을 닫을 때 죽는 백그라운드 스레드입니다.


나는 이것들에 대한 상대적인 리소스 사용에 대해 궁금했고 Windows 8에서 .net 4.0 릴리스 빌드를 사용하여 2012 듀얼 코어 Intel i5 랩톱에서 벤치 마크를 실행했습니다. 스레드 풀은 평균 0.035ms가 소요되어 스레드는 평균 5.06을 차지했습니다 ms. 다시 말해 풀의 스레드는 많은 짧은 스레드 스레드에 대해 약 300 배 더 빠르게 시작되었습니다. 적어도 테스트 된 범위 (100-2000) 스레드에서 스레드 당 총 시간은 꽤 일정 해 보입니다.

이것은 벤치마킹 된 코드입니다.

    for (int i = 0; i < ThreadCount; i++) {
        Task.Run(() => { });
    }

    for (int i = 0; i < ThreadCount; i++) {
        var t = new Thread(() => { });
        t.Start();
    }

여기에 이미지 설명을 입력하십시오


이전 스레드를 확인하십시오.

언제 .Net에서 ThreadPool을 사용해서는 안됩니까?

요약하면 스레드 풀을 사용하면 좀 더 많은 제어를 할 수있는 반면 스레드 수명이 짧은 스레드를 많이 생성해야하는 경우 스레드 풀이 좋습니다.


Thread local storage is not a good idea with thread pools. It gives threads an "identity"; not all threads are equal anymore. Now thread pools are especially useful if you just need a bunch of identical threads, ready to do your work without creation overhead.


If you need a lot of threads, you probably want to use a ThreadPool. They re-use threads saving you the overhead of thread creation.

If you just need one thread to get something done, Thread is probably easiest.


The primary need for theadpool threads is to handle short little tasks that are expected to complete almost instantly. Hardware interrupt handlers often run in a stacking context which would not be suitable for non-kernel code, but a hardware interrupt handler may discover that a user-mode I/O completion callback should be run as soon as possible. Creating a new thread for the purpose of running such a thing would be massive overkill. Having a few pre-created threads which can be dispatched to run I/O completion callbacks or other similar things is much more efficient.

A key aspect of such threads is that if I/O completion methods always complete essentially instantaneously and never block, and the number of such threads that are presently running such methods is at least equal to the number of processors, the only way any other thread could run before one of the aforementioned methods finishes would be if one of the other methods blocks or its execution time exceeds a normal threading time-slice; neither of those should happen very often if the thread pool is used as intended.

If a method cannot be expected to exit within 100ms or so of when it starts execution, the method should be executed via some means other than the main thread pool. If one has a lot of tasks to perform which are CPU intensive but won't block, it may be helpful to dispatch them using a pool of application threads (one per CPU core) which is separate from the "main" threadpool, since using more threads than cores will be counterproductive when running non-blocking CPU-intensive tasks. If, however, a method will take a second or longer to execute, and will spend most of its time blocked, the method should likely be run in a dedicated thread, and should almost certainly not be run in a main-threadpool thread. If a long-running operation needs to be triggered by something like an I/O callback, one should either start a thread for the long-running operation in advance of the callback and have it wait on a monitor which the callback pulses, or else have the callback launch a new thread to perform the operation while the callback exits, effectively returning its own thread to the threadpool.


In general (I have never used .NET), a thread pool would be used for resource management purposes. It allows constraints to be configured into your software. It also may be done for performance reasons, as creation of new threads may be costly.

There may also be system specific reasons. In Java (again I don't know if this applies to .NET), the manager of the threads may apply thread specific variables as each thread is pulled from the pool, and unset them when they are returned (common way to pass something like an identity).

Example constraint: I only have 10 db connections, so I would only allow 10 worker threads for accessing the database.

This doesn't mean that you should not create your own threads, but there are conditions under which it makes sense to use a pool.


작성 될 스레드 수를 모르거나 제어 할 수없는 경우 풀을 사용하는 것이 좋습니다.

목록 컨트롤의 위치 변경 이벤트 (freez를 피하십시오)에서 데이터베이스의 일부 필드를 업데이트하기 위해 스레드를 사용하는 양식에 문제가 있습니다. 사용자가 목록 위치를 너무 빠르게 변경했기 때문에 데이터베이스에서 Access에 너무 많은 연결이 발생하는 데 5 분이 걸렸습니다.

기본 문제를 해결하는 다른 방법이 있다는 것을 알고 있습니다 (액세스 사용하지 않음 포함). 풀링은 좋은 시작입니다.

참고 URL : https://stackoverflow.com/questions/230003/thread-vs-threadpool

반응형