python 并行处理介绍

本文介绍了Python中的并行处理,包括GIL(全局解释器锁)如何影响多线程执行,以及multiprocessing模块如何通过多进程避免GIL问题。同时,文章提到了concurrent.futures模块的ProcessPoolExecutor类,用于实现多进程并行,但需要注意其在交互式解释器中无法工作的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.GIL介绍:
GIL(Global Interpreter Lock)又称全局解释器锁,是在CPython解释器下的一个独有问题(该问题只针对CPython,其他解释器下并没有)。在CPython解释器下处理多线程问题时,每个线程在执行时候都需要先获取GIL,保证同一时刻只有一个线程可以执行代码,即同一时刻只有一个线程使用CPU,也就是说多线程并不是真正意义上的同时执行。
2.multiprocess模块
multiprocessing库的出现很大程度上是为了弥补thread库因为GIL而低效的缺陷。它完整的复制了一套thread所提供的接口方便迁移。唯一的不同就是它使用了多进程而不是多线程。每个进程有自己的独立的GIL,因此也不会出现进程之间的GIL争抢。但是,它的引入会增加程序实现时线程间数据通讯和同步的困难。因为各个GIF锁之间数据无法共享、
3.concurrent.futures模块
concurrent.futures模块下的ProcessPoolExecutor类是一个进行多进程的类,该模块利用的是multiprocess,这也意味该模块只适用于可序列化的数据类型,即可以pickle。
代码:

import concurrent.futures
import math
import time


PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True


with concurrent.futures.ProcessPoolExecutor() as executor:
    time0 = time.time()
    print(executor.map(is_prime, PRIMES))
    time1 = time.time()
    print(time1 - time0)


time0 = time.time()
for i in PRIMES:
    print(is_prime(i))
time1 = time.time()
print(time1 - time0)
输出:
<generator object _chain_from_iterable_of_lists at 0x000002124BA06C00>
0.37488555908203125
True
True
True
True
True
False
2.6765103340148926

很明显加快了很多,另外从输出里面我们可以看到并行操作产生了一个生成器,为了得到输出结果我们可以将代码改为:

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

摘录一句python官方文档里的一句: **ProcessPoolExecutor will not work in the interactive interpreter.**所以必须用:

if __name__ == '__main__':
    main()

或者直接在函数添加全局变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值