使用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)

关于GIL和多线程串行的问题,更多的可以参考:
http://stackoverflow.com/questions/990102/python-global-interpreter-lock-gil-workaround-on-multi-core-systems-using-task
https://docs.python.org/dev/library/multiprocessing.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值