소개
Python의 다중 처리 모듈을 사용하면 프로세스를 생성하고 관리할 수 있으므로 컴퓨터의 다중 프로세서를 최대한 활용할 수 있습니다. 스레드가 동일한 메모리 공간을 공유하는 스레딩과 달리 각 프로세스에 대해 별도의 메모리 공간을 사용하여 병렬 실행을 달성하는 데 도움이 됩니다. 다음은 간단한 예와 함께 multiprocessing 모듈에서 일반적으로 사용되는 클래스 및 메소드 목록입니다.
1. 프로세스
Process 클래스는 멀티프로세싱 모듈의 핵심으로, 새로운 프로세스를 생성하고 실행할 수 있게 해줍니다.
from multiprocessing import Process def print_numbers(): for i in range(5): print(i) p = Process(target=print_numbers) p.start() # Starts a new process p.join() # Waits for the process to finish
2. 시작()
프로세스 활동을 시작합니다.
p = Process(target=print_numbers) p.start() # Runs the target function in a separate process
3. 가입([시간 초과])
join() 메소드가 호출된 프로세스가 종료될 때까지 호출 프로세스를 차단합니다. 선택적으로 시간 초과를 지정할 수 있습니다.
p = Process(target=print_numbers) p.start() p.join(2) # Waits up to 2 seconds for the process to finish
4. is_alive()
프로세스가 아직 실행 중이면 True를 반환합니다.
p = Process(target=print_numbers) p.start() print(p.is_alive()) # True if the process is still running
5. 현재_프로세스()
호출 프로세스를 나타내는 현재 Process 개체를 반환합니다.
from multiprocessing import current_process def print_current_process(): print(current_process()) p = Process(target=print_current_process) p.start() # Prints the current process info
6. 활성_어린이()
현재 살아있는 모든 Process 객체의 목록을 반환합니다.
p1 = Process(target=print_numbers) p2 = Process(target=print_numbers) p1.start() p2.start() print(Process.active_children()) # Lists all active child processes
7. CPU_카운트()
머신에서 사용할 수 있는 CPU 수를 반환합니다.
from multiprocessing import cpu_count print(cpu_count()) # Returns the number of CPUs on the machine
8. 수영장
풀 개체는 여러 입력 값에 걸쳐 함수 실행을 병렬화하는 편리한 방법을 제공합니다. 작업자 프로세스 풀을 관리합니다.
from multiprocessing import Pool def square(n): return n * n with Pool(4) as pool: # Pool with 4 worker processes result = pool.map(square, [1, 2, 3, 4, 5]) print(result) # [1, 4, 9, 16, 25]
9. 대기열
큐는 여러 프로세스가 서로 데이터를 전달하여 통신할 수 있도록 하는 공유 데이터 구조입니다.
from multiprocessing import Process, Queue def put_data(q): q.put([1, 2, 3]) def get_data(q): data = q.get() print(data) q = Queue() p1 = Process(target=put_data, args=(q,)) p2 = Process(target=get_data, args=(q,)) p1.start() p2.start() p1.join() p2.join()
10. 잠금
잠금을 사용하면 한 번에 하나의 프로세스만 공유 리소스에 액세스할 수 있습니다.
from multiprocessing import Process, Lock lock = Lock() def print_numbers(): with lock: for i in range(5): print(i) p1 = Process(target=print_numbers) p2 = Process(target=print_numbers) p1.start() p2.start() p1.join() p2.join()
11. 값과 배열
값 및 배열 개체를 사용하면 프로세스 간에 간단한 데이터 유형과 배열을 공유할 수 있습니다.
from multiprocessing import Process, Value def increment(val): with val.get_lock(): val.value += 1 shared_val = Value('i', 0) processes = [Process(target=increment, args=(shared_val,)) for _ in range(10)] for p in processes: p.start() for p in processes: p.join() print(shared_val.value) # Output will be 10
12. 파이프
파이프는 두 프로세스 간의 양방향 통신 채널을 제공합니다.
from multiprocessing import Process, Pipe def send_message(conn): conn.send("Hello from child") conn.close() parent_conn, child_conn = Pipe() p = Process(target=send_message, args=(child_conn,)) p.start() print(parent_conn.recv()) # Receives data from the child process p.join()
13. 관리자
관리자를 사용하면 여러 프로세스가 동시에 수정할 수 있는 목록 및 사전과 같은 공유 개체를 만들 수 있습니다.
from multiprocessing import Process, Manager def modify_list(shared_list): shared_list.append("New item") with Manager() as manager: shared_list = manager.list([1, 2, 3]) p = Process(target=modify_list, args=(shared_list,)) p.start() p.join() print(shared_list) # [1, 2, 3, "New item"]
14. 세마포어
세마포어를 사용하면 리소스에 대한 액세스를 제어하여 한 번에 특정 수의 프로세스만 액세스하도록 허용할 수 있습니다.
from multiprocessing import Process, Semaphore import time sem = Semaphore(2) # Only 2 processes can access the resource def limited_access(): with sem: print("Accessing resource") time.sleep(2) processes = [Process(target=limited_access) for _ in range(5)] for p in processes: p.start() for p in processes: p.join()
결론
Python의 다중 처리 모듈은 컴퓨터의 다중 프로세서를 최대한 활용하도록 설계되었습니다. Process를 사용한 프로세스 생성 및 관리부터 Lock 및 Semaphore를 사용한 공유 리소스 제어, Queue 및 Pipe를 통한 통신 촉진에 이르기까지 다중 처리 모듈은 Python 애플리케이션에서 작업을 병렬화하는 데 매우 중요합니다.
위 내용은 예제가 포함된 Python 다중 처리 모듈에 대한 빠른 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

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

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음