찾다
백엔드 개발파이썬 튜토리얼예제가 포함된 Python 다중 처리 모듈에 대한 빠른 가이드

A Quick Guide to the Python multiprocessing Module with Examples

소개

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 : 편집과 해석에 대한 깊은 다이빙파이썬 : 편집과 해석에 대한 깊은 다이빙May 12, 2025 am 12:14 AM

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?May 12, 2025 am 12:09 AM

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

루프 대 파이썬의 루프 : 주요 차이점 설명루프 대 파이썬의 루프 : 주요 차이점 설명May 12, 2025 am 12:08 AM

forloopsareideal when

루프를위한 것 및 기간 : 실용 가이드루프를위한 것 및 기간 : 실용 가이드May 12, 2025 am 12:07 AM

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다May 12, 2025 am 12:05 AM

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

동일한 요소를 가진 Python Concatenate 목록동일한 요소를 가진 Python Concatenate 목록May 11, 2025 am 12:08 AM

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

해석 대 컴파일 언어 : Python 's Place해석 대 컴파일 언어 : Python 's PlaceMay 11, 2025 am 12:07 AM

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

루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?May 11, 2025 am 12:05 AM

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

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

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

뜨거운 도구

맨티스BT

맨티스BT

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

SublimeText3 영어 버전

SublimeText3 영어 버전

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

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

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

DVWA

DVWA

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

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음