스레드 풀 (Thread Pool)
Python 에서는 미리 정의된 스레드 집합을 사용하여 작업을 동시에 실행하기 위해 스레드 풀을 사용할 수 있습니다. 스레드 풀을 사용하면 각 작업에 대해 스레드를 생성하고 소멸하는 오버헤드를 피할 수 있어 성능을 향상시킬 수 있다는 장점이 있습니다.
Python 의 concurrent.futures 모듈은 스레드 풀을 생성하고 작업을 제출할 수 있는 ThreadPoolExecutor 클래스를 제공합니다. 다음은 예시입니다.
WebIDE 에서 thread_pool_range.py라는 프로젝트를 생성하고 다음 내용을 입력합니다.
import concurrent.futures
## Define a function to be executed in multiple threads with two arguments
def my_func(arg1, arg2):
## Define the tasks performed by the thread here
print(f"Hello from my thread with args {arg1} and {arg2}")
## Create a ThreadPoolExecutor object with a maximum of 5 worker threads
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
## Submit each task (function call with its arguments) to the executor for processing in a separate thread
## The submit() method returns a Future object representing the result of the asynchronous computation
for i in range(10):
executor.submit(my_func, i, i+1)
이 예제에서는 두 개의 인수를 받는 my_func 함수를 정의합니다. 최대 5 개의 작업자 스레드를 가진 ThreadPoolExecutor를 생성합니다. 그런 다음, 숫자 범위를 반복하면서 executor.submit() 메서드를 사용하여 스레드 풀에 작업을 제출합니다. 제출된 각 작업은 사용 가능한 작업자 스레드 중 하나에서 실행됩니다.
팁: ThreadPoolExecutor 객체는 컨텍스트 관리자로 사용됩니다. 이렇게 하면 with 블록 내부의 코드가 완료될 때 모든 스레드가 제대로 정리됩니다.
다음 명령을 사용하여 스크립트를 실행합니다.
python thread_pool_range.py
submit() 메서드는 제출된 작업의 결과를 나타내는 Future 객체를 즉시 반환합니다. Future 객체의 result() 메서드를 사용하여 작업의 반환 값을 검색할 수 있습니다. 작업에서 예외가 발생하면 result()를 호출하면 해당 예외가 발생합니다.
또한 ThreadPoolExecutor 클래스의 map() 메서드를 사용하여 동일한 함수를 항목 모음에 적용할 수 있습니다. 예를 들어, WebIDE 에서 thread_pool_map.py라는 프로젝트를 생성하고 다음 내용을 입력합니다.
import concurrent.futures
## Define a function to be executed in multiple threads
def my_func(item):
## Define the tasks performed by the thread here
print(f"Hello from my thread with arg {item}")
## Create a list of items to be processed by the threads
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
## Create a ThreadPoolExecutor object with a maximum of 5 worker threads
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
## Submit each item to the executor for processing in a separate thread
## The map() method automatically returns the results in order
executor.map(my_func, items)
이 예제에서는 하나의 인수를 받는 my_func 함수를 정의합니다. 항목 목록을 생성하고 executor.map() 메서드를 사용하여 스레드 풀에 제출합니다. 목록의 각 항목은 my_func에 인수로 전달되며, 각 항목은 사용 가능한 작업자 스레드 중 하나에서 실행됩니다.
다음 명령을 사용하여 스크립트를 실행합니다.
python thread_pool_map.py
thread_pool_range.py 및 thread_pool_map.py에서 얻은 결과는 동일합니다.