Python에서 여러 작업을 동시에 실행하는 경우 concurrent.futures 모듈은 강력하고 간단한 도구입니다. 이 글에서는 ThreadPoolExecutor를 사용하여 작업을 병렬로 실행하는 방법과 실제 예제를 살펴보겠습니다.
ThreadPoolExecutor를 사용하는 이유는 무엇입니까?
Python에서 스레드는 네트워크 호출이나 파일 읽기/쓰기 작업과 같이 I/O 작업이 지배적인 작업에 적합합니다. ThreadPoolExecutor를 사용하면 다음을 수행할 수 있습니다.
- 스레드를 수동으로 관리하지 않고도 여러 작업을 동시에 실행
- 활성 스레드 수를 제한하여 시스템에 부담을 주지 않도록 하세요.
- 직관적인 API를 활용하여 쉽게 결과를 수집하세요.
예: 병렬로 작업 실행
개념 이해를 위해 간단한 예를 살펴보겠습니다.
코드
from concurrent.futures import ThreadPoolExecutor import time # Function simulating a task def task(n): print(f"Task {n} started") time.sleep(2) # Simulates a long-running task print(f"Task {n} finished") return f"Result of task {n}" # Using ThreadPoolExecutor def execute_tasks(): tasks = [1, 2, 3, 4, 5] # List of tasks results = [] # Create a thread pool with 3 simultaneous threads with ThreadPoolExecutor(max_workers=3) as executor: # Execute tasks in parallel results = executor.map(task, tasks) return list(results) if __name__ == "__main__": results = execute_tasks() print("All results:", results)
예상 출력
이 코드를 실행하면 다음과 같은 내용이 표시됩니다(약간 병렬 순서로).
Task 1 started Task 2 started Task 3 started Task 1 finished Task 4 started Task 2 finished Task 5 started Task 3 finished Task 4 finished Task 5 finished All results: ['Result of task 1', 'Result of task 2', 'Result of task 3', 'Result of task 4', 'Result of task 5']
max_workers=3이므로 작업 1, 2, 3이 동시에 시작됩니다. 다른 작업(4 및 5)은 스레드를 사용할 수 있을 때까지 기다립니다.
언제 사용하나요?
일반적인 사용 사례:
- API에서 데이터 가져오기: 여러 URL을 동시에 로드합니다.
- 파일 처리: 여러 파일을 동시에 읽고, 쓰고, 변환합니다.
- 작업 자동화: 여러 스크립트 또는 명령을 병렬로 실행합니다.
모범 사례
-
스레드 수 제한:
- 스레드가 너무 많으면 CPU에 과부하가 걸리거나 병목 현상이 발생할 수 있습니다.
-
예외 처리:
- 한 작업이 실패하면 전체 풀에 영향을 미칠 수 있습니다. 함수에서 예외를 포착하세요.
-
CPU 바인딩 작업에 ProcessPoolExecutor 사용:
- 스레드는 Python의 GIL(Global Interpreter Lock)로 인해 과도한 계산에 적합하지 않습니다.
고급 예: 병렬로 URL 가져오기
다음은 실제 예입니다. 여러 URL을 동시에 가져오는 것입니다.
import requests from concurrent.futures import ThreadPoolExecutor # Function to fetch a URL def fetch_url(url): try: response = requests.get(url) return f"URL: {url}, Status: {response.status_code}" except Exception as e: return f"URL: {url}, Error: {e}" # List of URLs to fetch urls = [ "https://example.com", "https://httpbin.org/get", "https://jsonplaceholder.typicode.com/posts", "https://invalid-url.com" ] def fetch_all_urls(urls): with ThreadPoolExecutor(max_workers=4) as executor: results = executor.map(fetch_url, urls) return list(results) if __name__ == "__main__": results = fetch_all_urls(urls) for result in results: print(result)
결론
ThreadPoolExecutor는 Python에서 스레드 관리를 단순화하고 I/O 바인딩 작업 속도를 높이는 데 이상적입니다. 단 몇 줄의 코드만으로 작업을 병렬화하고 귀중한 시간을 절약할 수 있습니다.
위 내용은 # `ThreadPoolExecutor`로 Python 작업 향상의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.

"for"and "while"loopsare : 1) "에 대한"loopsareIdealforitertatingOverSorkNowniterations, whide2) "weekepindiTeRations.Un

Python에서는 다양한 방법을 통해 목록을 연결하고 중복 요소를 관리 할 수 있습니다. 1) 연산자를 사용하거나 ()을 사용하여 모든 중복 요소를 유지합니다. 2) 세트로 변환 한 다음 모든 중복 요소를 제거하기 위해 목록으로 돌아가지 만 원래 순서는 손실됩니다. 3) 루프 또는 목록 이해를 사용하여 세트를 결합하여 중복 요소를 제거하고 원래 순서를 유지하십시오.

fastestestestedforListCancatenationInpythondSpendsonListsize : 1) Forsmalllist, OperatoriseFficient.2) ForlargerLists, list.extend () OrlistComprehensionIsfaster, withextend () morememory-efficientBymodingListsin-splace.

toInsertElmentsIntoapyThonList, useAppend () toaddtotheend, insert () foraspecificposition, andextend () andextend () formultipleElements.1) useappend () foraddingsingleitemstotheend.2) useinsert () toaddatespecificindex, 그러나)

pythonlistsareimplementedesdynamicarrays, notlinkedlists.1) thearestoredIntIguousUousUousUousUousUousUousUousUousUousInSeripendExeDaccess, LeadingSpyTHOCESS, ImpactingEperformance

PythonoffersfourmainmethodstoremoveElementsfromalist : 1) 제거 (값) 제거 (값) removesthefirstoccurrencefavalue, 2) pop (index) 제거 elementatAspecifiedIndex, 3) delstatemeveselementsByindexorSlice, 4) RemovesAllestemsfromTheChmetho

Toresolvea "permissionDenied"오류가 발생할 때 오류가 발생합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SecList
SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기