Python 多處理模組快速指南及範例

WBOY
發布: 2024-09-12 14:17:10
原創
753 人瀏覽過

A Quick Guide to the Python multiprocessing Module with Examples

介紹

Python 中的多處理模組可讓您建立和管理進程,使您能夠充分利用機器上的多個處理器。它透過為每個進程使用單獨的記憶體空間來幫助您實現並行執行,這與線程共享相同記憶體空間的線程不同。以下是多處理模組中常用的類別和方法的列表,並附有簡短的範例。

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

傳回目前活動的所有 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_count()

傳回機器上可用的 CPU 數量。

from multiprocessing import cpu_count

print(cpu_count())  # Returns the number of CPUs on the machine
登入後複製

8. 泳池

Pool 物件提供了一種跨多個輸入值並行執行函數的便捷方法。它管理一個工作進程池。

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. 值和數組

Value 和 Array 物件允許在進程之間共享簡單的資料類型和陣列。

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!