python多进程想必大部分人都用到过,可以充分利用多核CPU让代码效率更高效。

我们看看multiprocessing.pool.Pool.map的官方用法

map(func, iterable[, chunksize])
A parallel equivalent of the map() built-in function (it supports only one iterable argument though). It blocks until the result is ready. This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer.

一、多参数传入如何变成一个参数

map的用法,函数func只允许一个可迭代的参数传递进去。

如果我们需要传递多个参数时怎么办呢,

一种方法是把多个参数放入到一个list或者元祖里当做一个参数传入func中

还有一种是使用偏函数,偏函数(Partial function)是通过将一个函数的部分参数预先绑定为某些值,从而得到一个新的具有较少可变参数的函数。在Python中,可以通过functools中的partial高阶函数来实现偏函数功能。偏函数partial的源码如下:

def partial(func, *args, **keywords):
"""New function with partial application of the given arguments
and keywords.
"""
if hasattr(func, 'func'):
args = func.args + args
tmpkw = func.keywords.copy()
tmpkw.update(keywords)
keywords = tmpkw
del tmpkw
func = func.func def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc

使用方法也很简单,比如我们有一个func函数,里面要传入texts,lock, data三个参数,但是我们想要用多进程把data分别传入进去计算,那么我们就可以先用partial函数,将texts和lock先固定到函数里组成一个新的函数,然后新函数传入data一个参数就可以了

from functools import partial
def func(texts, lock, data):
...... pt = partial(func, tests, lock) # 新函数pt只需要传入一个参数data

这我们就可以对pt函数套用pool.map函数并且只传入一个参数data里。

二、多进程内存复制

python对于多进程中使用的是copy on write机制,python 使用multiprocessing来创建多进程时,无论数据是否不会被更改,子进程都会复制父进程的状态(内存空间数据等)。所以如果主进程耗的资源较多时,不小心就会造成不必要的大量的内存复制,从而可能导致内存爆满的情况。

进程的启动有spawn、fork、forkserver三种方式

spawn:调用该方法,父进程会启动一个新的python进程,子进程只会继承运行进程对象run()方法所需的那些资源。特别地,子进程不会继承父进程中不必要的文件描述符和句柄。与使用forkforkserver相比,使用此方法启动进程相当慢。

Available on Unix and Windows. The default on Windows.

fork:父进程使用os.fork()来fork Python解释器。子进程在开始时实际上与父进程相同,父进程的所有资源都由子进程继承。请注意,安全创建多线程进程尚存在一定的问题。

Available on Unix only. The default on Unix.

forkserver:当程序启动并选择forkserverstart方法时,将启动服务器进程。从那时起,每当需要一个新进程时,父进程就会连接到服务器并请求它fork一个新进程。 fork服务器进程是单线程的,因此使用os.fork()是安全的。没有不必要的资源被继承。

Available on Unix platforms which support passing file descriptors over Unix pipes.

要选择以上某一种start方法,请在主模块的if __name__ == '__ main__'子句中使用mp.set_start_method()。并且mp.set_start_method()在一个程序中仅仅能使用一次。

import multiprocessing as mp

def foo(q):
q.put('hello') if __name__ == '__main__':
mp.set_start_method('spawn')
q = mp.Queue()
p = mp.Process(target=foo, args=(q,))
p.start()
print(q.get())
p.join()

设置maxtasksperchild=1,因此,每个任务完成后都不会重新生成进程,

对pool.map的调用中指定chunksize = 1.这样iterable中的多个项目将不会从工作进程的感知捆绑到一个“任务”中:

import multiprocessing
import time
import os def f(x):
print("PID: %d" % os.getpid())
time.sleep(x)
complex_obj = 5 #more complex axtually
return complex_obj if __name__ == '__main__':
multiprocessing.set_start_method('spawn')
pool = multiprocessing.Pool(4, maxtasksperchild=1)
pool.map(f, [5]*30, chunksize=1)
pool.close()

三、多进程间通讯

还有一种情况是,多进程间要相互之间通讯,比如我每一个进程的结果都要存入到texts这个list里。当然要把这个texts当做参数传入到函数里面,但是一般的list并不能共享给所有的进程,我们需要用multiprocessing.Manager().list()建立的list才可以用于进程间通讯,防止冲突,还要对texts加上锁,防止操作冲突。注意multiprocessing.Lock() 创建的锁不能传递,需要使用multiprocessing.Manager().Lock()来创建。multiprocessing.Manager()可创建字典,也可创建list,lock,它创建的变量可用于多进程间传递才不会出错。比如以下代码:

texts = multiprocessing.Manager().list()
lock = multiprocessing.Manager().Lock()
pool = multiprocessing.Pool(processes=4)
data = list(range(20))
pt = partial(func, texts, lock)
pool.map(pt, data)
pool.close()
pool.join()

python多进程multiprocessing Pool相关问题的更多相关文章

  1. Python 多进程 multiprocessing.Pool类详解

    Python 多进程 multiprocessing.Pool类详解 https://blog.csdn.net/SeeTheWorld518/article/details/49639651

  2. python中multiprocessing.pool函数介绍_正在拉磨_新浪博客

    python中multiprocessing.pool函数介绍_正在拉磨_新浪博客     python中multiprocessing.pool函数介绍    (2010-06-10 03:46:5 ...

  3. python多进程-----multiprocessing包

    multiprocessing并非是python的一个模块,而是python中多进程管理的一个包,在学习的时候可以与threading这个模块作类比,正如我们在上一篇转载的文章中所提,python的多 ...

  4. Python 多进程multiprocessing

    一.python多线程其实在底层来说只是单线程,因此python多线程也称为假线程,之所以用多线程的意义是因为线程不停的切换这样比串行还是要快很多.python多线程中只要涉及到io或者sleep就会 ...

  5. python ---多进程 Multiprocessing

    和 threading 的比较 多进程 Multiprocessing 和多线程 threading 类似, 他们都是在 python 中用来并行运算的. 不过既然有了 threading, 为什么 ...

  6. Python多进程multiprocessing使用示例

    mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多. import multipr ...

  7. 操作系统OS,Python - 多进程(multiprocessing)、多线程(multithreading)

    多进程(multiprocessing) 参考: https://docs.python.org/3.6/library/multiprocessing.html 1. 多进程概念 multiproc ...

  8. Python多进程multiprocessing

    import multiprocessing import time # 具体的处理函数,负责处理单个任务 def func(msg): # for i in range(3): print (msg ...

  9. python多进程(multiprocessing)

    最近有个小课题,需要用到双进程,翻了些资料,还算圆满完成任务.记录一下~ 1.简单地双进程启动 同时的调用print1()和print2()两个打印函数,代码如下: #/usr/bin/python ...

随机推荐

  1. Opencv中图像height width X 轴 Y轴 rows cols之间的对应关系

    这里做一个备忘录:

  2. VUE中 $on, $emit, v-on三者关系

    VUE中 $on, $emit, v-on三者关系 每个vue实例都实现了事件借口 使用$on(eventName)监听事件 使用$emit(eventName)触发事件 若把vue看成家庭(相当于一 ...

  3. 用dotnet core 搭建web服务器(一)http server

    环境说明 dotnet core,开发需要安装dotnetcore sdk,运行需要安装 dotnetcore runtime 运行目前几乎支持所有常见平台 开发推荐windows10 平台 首先安装 ...

  4. [译]Vulkan教程(18)命令buffers

    [译]Vulkan教程(18)命令buffers Command buffers 命令buffer Commands in Vulkan, like drawing operations and me ...

  5. Linux查看文件或文件夹大小du命令

    du命令用于显示目录或文件的大小. du会显示指定的目录或文件所占用的磁盘空间. 语法: du [-abcDhHklmsSx][-L <符号连接>][-X <文件>][--bl ...

  6. javascript截取字符串的最后几个字符

    在JavaScript中截取字符串一般是使用内置的substring()方法和substr()方法,这两个方法功能都很强大,也都能实现截取字符串中的最后几个字符. substring()方法 Java ...

  7. wireshark和tcpdump抓包TCP乱序和重传怎么办?PCAP TCP排序工具分享

    点击上方↑↑↑蓝字[协议分析与还原]关注我们 " 介绍TCP排序方法,分享一个Windows版的TCP排序工具." 在分析协议的过程中,不可避免地需要抓包. 无论抓包条件如何优越, ...

  8. Last 2 dimensions of the array must be square

    这个报错是因为我们在求解行列式的值的时候使用了: np.linalg.det(D) 但是D必须是方阵才可以进行运算,不是方阵则会报错,我们把之前的行列式更改为方阵就不会再报错了,当然这也是numpy自 ...

  9. 005.MongoDB索引及聚合

    一 MongoDB 索引 索引通常能够极大的提高查询的效率,如果没有索引,MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录. 这种扫描全集合的查询效率是非常低的,特别在处 ...

  10. 线性代数笔记24——微分方程和exp(At)

    原文:https://mp.weixin.qq.com/s/COpYKxQDMhqJRuMK2raMKQ 微分方程指含有未知函数及其导数的关系式,解微分方程就是找出未知函数.未知函数是一元函数的,叫常 ...