搜索
首页后端开发Python教程Python 多处理模块快速指南及示例

A Quick Guide to the Python multiprocessing Module with Examples

Introduction

The multiprocessing module in Python allows you to create and manage processes, enabling you to take full advantage of multiple processors on a machine. It helps you achieve parallel execution by using separate memory spaces for each process, unlike threading where threads share the same memory space. Here's a list of commonly used classes and methods in the multiprocessing module with brief examples.

1. Process

The Process class is the core of the multiprocessing module, allowing you to create and run new processes.

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. start()

Starts the process’s activity.

p = Process(target=print_numbers)
p.start()  # Runs the target function in a separate process

3. join([timeout])

Blocks the calling process until the process whose join() method is called terminates. Optionally, you can specify a timeout.

p = Process(target=print_numbers)
p.start()
p.join(2)  # Waits up to 2 seconds for the process to finish

4. is_alive()

Returns True if the process is still running.

p = Process(target=print_numbers)
p.start()
print(p.is_alive())  # True if the process is still running

5. current_process()

Returns the current Process object representing the calling 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. active_children()

Returns a list of all Process objects currently alive.

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_count()

Returns the number of CPUs available on the machine.

from multiprocessing import cpu_count

print(cpu_count())  # Returns the number of CPUs on the machine

8. Pool

A Pool object provides a convenient way to parallelize execution of a function across multiple input values. It manages a pool of worker processes.

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. Queue

A Queue is a shared data structure that allows multiple processes to communicate by passing data between them.

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. Lock

A Lock ensures that only one process can access a shared resource at a time.

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. Value and Array

The Value and Array objects allow sharing simple data types and arrays between processes.

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. Pipe

A Pipe provides a two-way communication channel between two processes.

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. Manager

A Manager allows you to create shared objects, such as lists and dictionaries, that multiple processes can modify concurrently.

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. Semaphore

A Semaphore allows you to control access to a resource, permitting only a certain number of processes to access it at a time.

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()

Conclusion

The multiprocessing module in Python is designed to take full advantage of multiple processors on a machine. From creating and managing processes using Process, to controlling shared resources with Lock and Semaphore, and facilitating communication through Queue and Pipe, the multiprocessing module is crucial for parallelizing tasks in Python applications.

以上是Python 多处理模块快速指南及示例的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python的混合方法:编译和解释合并Python的混合方法:编译和解释合并May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增强效率和通用性。

了解python的' for”和' then”循环之间的差异了解python的' for”和' then”循环之间的差异May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串联列表与重复Python串联列表与重复May 08, 2025 am 12:09 AM

在Python中,可以通过多种方法连接列表并管理重复元素:1)使用 运算符或extend()方法可以保留所有重复元素;2)转换为集合再转回列表可以去除所有重复元素,但会丢失原有顺序;3)使用循环或列表推导式结合集合可以去除重复元素并保持原有顺序。

Python列表串联性能:速度比较Python列表串联性能:速度比较May 08, 2025 am 12:09 AM

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

您如何将元素插入python列表中?您如何将元素插入python列表中?May 08, 2025 am 12:07 AM

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

Python是否列表动态阵列或引擎盖下的链接列表?Python是否列表动态阵列或引擎盖下的链接列表?May 07, 2025 am 12:16 AM

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他们areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

如何从python列表中删除元素?如何从python列表中删除元素?May 07, 2025 am 12:15 AM

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)删除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?试图运行脚本时,应该检查是否会遇到'权限拒绝”错误?May 07, 2025 am 12:12 AM

toresolvea“ dermissionded”错误Whenrunningascript,跟随台词:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。