1. 程式人生 > >使用multiprocessing包規避Python GIL多執行緒序列問題

使用multiprocessing包規避Python GIL多執行緒序列問題

1.Python是單核的,只能充分利用1個CPU的1個核
2.對一個多執行緒程式,執行緒間即使啟動多個子直譯器,依然有GIL這個全域性鎖,會引起序列。
序列是libpython導致的。
3.要使用Python做平行計算或規避多執行緒序列的問題。使用multiprocessing包時最好的選擇。
在多程序環境下,每個程序可以執行一個直譯器,互相之間是獨立的,沒有鎖。multiprocessing包提供了程序呼叫實現的封裝。包括啟動程序,程序間訊息佇列,程序池等等。
這裡舉一個簡單的例子,可以實現任意函式的IPC或者說RPC封裝,實現任意函式在子程序中執行並返回結果給主程序:

multiprocessing is a package that supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads. Due to this, the multiprocessing module allows the programmer to fully leverage multiple processors on a given machine. It runs on both Unix and Windows.

from multiprocessing import Process
from multiprocessing import Queue

def f(a,b):
    return a+b

def wrapper(q,a,b):
    q.put(f(a,b))

def fRPC(a,b):
    q = Queue()
    p = Process(target=wrapper, args=(q,a,b))
    p.start()
    print(q.get())
    p.join()

fRPC(1,2)