Python_多进程
Python 多进程库 multiprocessing ,支持子进程、通信、数据共享、执行不同形式的同步
多进程,绕过gil ,实现多核的利用,多进程也是原生进程,由操作系统维护
在pycharm中,可能没有办法正常使用multiprocessing.Process,最好是在Linux中运行
| Process | 用于创建进程模块 |
| Pool | 用于创建管理进程池 |
| Queue | 用于进程通信,资源共享 |
| Pipe | 用于管道通信 |
| Manager | 用于资源共享,同步进程 |
1.Process类
Process(group = None,target =None,name=None, args=[ ], kwargs={ })
| group | 线程组 |
| target | 要执行的方法 |
| name | 进程名 |
| args/kwargs | 要传入方法的参数 |
process属性&方法:
| authkey | 进程的身份验证密钥 |
| daemon | 同thread的setDaemon,守护进程 |
| exitcode | 进程运行时为None,若为—N,则表示被信号N结束 |
| pid | 进程号 |
| name | 进程名 |
| is_alive() | 返回进程是否正在运行 |
| join([timeout]) | 阻塞到线程结束或到timeout值 |
| start() | 进程准备就绪,等待CPU调度 |
| run() | start()调用run方法,如果实例进程时未制定传入target,start执行默认run()方法。 |
| terminate() | 不管任务是否完成,立即停止工作进程 |
多进程的创建:
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''多进程的创建'''
from multiprocessing import Process
import time def fun(name):
time.sleep(1)
print('hello,%s' % name)
print('----') if __name__ =='__main__':
for i in range(5): # 进程同步
p = Process(target=fun, args=('Presley',))
p.start()
p.join()
print('结束。')
多进程
进程id :
#!/usr/bin/python3
# -*- coding:utf-8 -*- from multiprocessing import Process
import os
def info(title):
print(title)
print('moudle name :',__name__)
print('parent process id ', os.getppid())
print('process id ', os.getpid()) if __name__ =='__main__':
info('hei. ') # pycharm id和 主进程id
for i in range(3):
p = Process(target=info, args=('Presley',)) # 主进程id 和 info 子进程id
p.start()
p.join()
hei.
moudle name : __main__
parent process id 1610
process id 1826
Presley
moudle name : __main__
parent process id 1826
process id 1827
Presley
moudle name : __main__
parent process id 1826
process id 1828
Presley
moudle name : __main__
parent process id 1826
process id 1829
result
2.Queue类
不同进程间内存是不共享的,想要实现两个进程间的数据交换,可以用Queue进行进程间通讯
queue是在多进程中做了一层封装的队列,以保证在当前进程里进程安全
方法:queue
进程中的队,以保证进程安全
from multiprocessing import Process,Queue
def info(q):
# global q # 错误,queue中 ,global 不行,因为子进程无法访问父进程的内存数据
q.put([34, None, 'yes']) if __name__ =='__main__':
q = Queue()
for i in range(3):
p = Process(target=info, args=[q,]) # 多个子进程的数据可以都可以放父进程数据
p.start()
print('来自父进程%s:%s'%(i, q.get()))
p.join()
多进程_queue
来自父进程0:[34, None, 'yes']
来自父进程1:[34, None, 'yes']
来自父进程2:[34, None, 'yes']
result
3.Pipe类
管道操作(双向队列):会返回一对对象,管道的两端分别赋给子进程和父进程
和队列操作差不多,所以一般运用队列较多
方法:
| send() | 发送序列 |
| recv() | 接收序列 |
| fileno() | 返回一个整型的文件描述符 |
| close() | 退出 |
| poll() | 判断子进程是否结束 |
| send_bytes() | 以bytes格式发送序列 |
| recv_bytes() | 以bytes格式接收序列 |
from multiprocessing import Process,Pipe
import time
def info(conn):
time.sleep(0.5)
conn.send([32,None,'ni hao wa']) conn.close() if __name__=='__main__':
conn_parent ,conn_child = Pipe()
print(conn_parent.fileno()) for i in range(3):
p = Process(target=info,args=(conn_child,))
print(bool(conn_child.poll)) # 进程是否结束
p.start()
# 如果没有消息可接收,recv方法会一直阻塞。如果管道已经被关闭,那么recv方法会抛出EOFError。
print('父端接收%s:%s'% (i,conn_parent.recv())) p.join()
多进程_Pipe
200
True
父端接收0:[32, None, 'ni hao wa']
True
父端接收1:[32, None, 'ni hao wa']
True
父端接收2:[32, None, 'ni hao wa']
result
4.Manager
通过Manager可以简单的使用list,dict,Namespace,Lock,RLock,Semaphore,BoundedSemaphore,Condition,Event,Barries,Value+Arrary等类型的高级接口
Manager()返回的manager对象控制了一个server进程,此进程包含的python对象可以被其他的进程通过proxies来访问。从而达到多进程间数据通信且安全
例:对list,dict的应用例子:
#!/usr/bin/python3
# -*- coding:utf-8 -*-
from multiprocessing import Process,Manager def fun(d,l,n):
d[2] = ''
d['e'] = 'e'
d[34] = None
l.append(n)
print(l) if __name__ == '__main__':
with Manager() as manager:
d = manager.dict()
l = manager.list()
join_list = []
for i in range(6):
p = Process(target=fun, args=(d,l,i))
p.start()
join_list.append(p)
for res in join_list:
res.join()
print(l)
print(d)
example
[5]
[5, 2]
[5, 2, 3]
[5, 2, 3, 0]
[5, 2, 3, 0, 4]
[5, 2, 3, 0, 4, 1]
[5, 2, 3, 0, 4, 1]
[5, 2, 3, 0, 4, 1]
[5, 2, 3, 0, 4, 1]
[5, 2, 3, 0, 4, 1]
[5, 2, 3, 0, 4, 1]
[5, 2, 3, 0, 4, 1]
{2: '', 'e': 'e', 34: None}
result
Manager的详细参考:https://www.aliyun.com/jiaocheng/490316.html
5.Pool 类(进程池)
当进程数过多时,用于限制进程数
异步:进程并行
同步:进程串行
方法:
| apply_async(func,args,kwds,callback) |
进程异步,并行(func:执行一个函数,args/ dwds:进程参数,callback:Foo执行结果返回到callback执行的函数中) |
| apply(func,args,kwds) | 进程同步,串行 |
| close() | 关闭进程池 |
| terminate() | 结束工作进程,不在处理未完成的任务 |
| join() | 主进程阻塞,等待子进程执行完毕 |
from multiprocessing import Pool,freeze_support
import time def Foo(i):
time.sleep(1)
print('exec..')
return i+100 # 返回到Bar中 def Bar(arg):
print('来自Foo 的i :',arg) # 接收 Foo中 的返回值 if __name__ == '__main__':
freeze_support() # 仅在Windows上才导入此模块进程程序才不会出错,Linux上不用
pool = Pool(5) # 限制每次进行的进程数为 5
for i in range(10):
pool.apply_async(func=Foo, args=(i,),callback=Bar) # 进程异步 # callback 把前面func的放在Bar中打印
# pool.apply(func=Foo, args=(i,)) # 同步,串行 # 没有callback属性
print('结束。。')
pool.close() # 注意:join必须放在close()后面,否则将不会等待子进程打印结束,而直接结束
pool.join()
进程池
结束。。
exec..
exec..
exec..
exec..
exec..
来自Foo 的i : 104
来自Foo 的i : 102
来自Foo 的i : 103
来自Foo 的i : 100
来自Foo 的i : 101
exec..
exec..
exec..
exec..
exec..
来自Foo 的i : 105
来自Foo 的i : 106
来自Foo 的i : 107
来自Foo 的i : 108
来自Foo 的i : 109
异步结果
exec..
exec..
exec..
exec..
exec..
exec..
exec..
exec..
exec..
exec..
结束。。
同步结果
Python_多进程的更多相关文章
- Python_多进程_pool进程池
多进程典型案例: 1.将子进程的进程名作为列表中的元素,在父进程中遍历(异步)执行 #coding: utf-8 from multiprocessing import Pool import os, ...
- python_并发编程——多进程的第二种启动方式
1.多进程的第二种启动方式 import os from multiprocessing import Process # 创建一个自定义类,继承Process类 class MyProcess(Pr ...
- python_并发编程——多进程
from multiprocessing import Process import os def func1(): print('子进程1',os.getpid()) #子进程:获取当前进程的进程号 ...
- python_多线程多进程
多线程,适用于IO密集型任务 IO,input,output缩写,包括网路io(比如上传下载),磁盘io,(比如数据库读写),CPU操作不频繁 多进程,适用于CPU密集型任务 数据分析,算法,依赖CP ...
- Python中的多进程与多线程(一)
一.背景 最近在Azkaban的测试工作中,需要在测试环境下模拟线上的调度场景进行稳定性测试.故而重操python旧业,通过python编写脚本来构造类似线上的调度场景.在脚本编写过程中,碰到这样一个 ...
- 取代SharedPreferences的多进程解决方案
Android的SharedPreferences用来存储一些键值对, 但是却不支持跨进程使用. 跨进程来用的话, 当然是放在数据库更可靠啦, 本文主要是给作者的新库PreferencesProvid ...
- python 多进程使用总结
python中的多进程主要使用到 multiprocessing 这个库.这个库在使用 multiprocessing.Manager().Queue时会出问题,建议大家升级到高版本python,如2 ...
- Nginx深入详解之多进程网络模型
一.进程模型 Nginx之所以为广大码农喜爱,除了其高性能外,还有其优雅的系统架构.与Memcached的经典多线程模型相比,Nginx是经典的多进程模型.Nginx启动后以daemon ...
- Python的多线程(threading)与多进程(multiprocessing )
进程:程序的一次执行(程序载入内存,系统分配资源运行).每个进程有自己的内存空间,数据栈等,进程之间可以进行通讯,但是不能共享信息. 线程:所有的线程运行在同一个进程中,共享相同的运行环境.每个独立的 ...
随机推荐
- 深入理解AMQP协议
深入理解AMQP协议 2018年10月22日 12:32:16 一剑何风情 阅读数:1941 文章目录 一.AMQP 是什么 二.AMQP模型 工作过程 深入理解 三.Exchange交换机 默认 ...
- SQLSERVER 实现三元运算符
三元运算符在很多种编程语言中都存在,那么在SQL Server中有没有呢? 很遗憾,SQL server中并没有这个功能,三元运算符是什么呢? 这是一段表达式:[条件 ? 满足返回值 : 不满足返回值 ...
- 「CF1154F」Shovels Shop【背包DP】
题目链接 [洛谷传送门] 题解 非常简单的背包. \(f[i]\)表示购买\(i\)个物品所需要最少的花费. 不考虑免费的限制条件,那么一定是选择前\(k\)个双鞋子. 那么加入免费的条件,那么还是要 ...
- 忘掉Ghost!利用Win10自带功能,玩转系统备份&恢复 -- 系统重置
之前几篇介绍的如何备份.恢复系统,在遇到问题的时候可以轻松应对. 如果系统出现问题,还可以正常启动,但是之前没有备份过系统,那该怎么办? 碰到这种问题,可以使用Win10系统的“系统重置”功能: 按照 ...
- Python终极coding
作为一名程序员,除了需要具备解决问题的思路以外,代码的质量和简洁性也很关键.因为从一个人的代码可以直接看出你的基本功.对于Python而言,这就意味着你需要对Python的内置功能和库有很深入的了解. ...
- spring boot本地调试服务器部署项目
项目本地测试然后发布到服务器上,各种BUG层出不穷.那么下面配置下,然后在本地调试部署在服务器上的程序吧 一.首先idea打开你的项目,服务器上传打包的程序.然后如下命令启动(linux),绿色参数为 ...
- wxpython多线程间通信
#!bin/bash/python # -*- coding=utf-8 -*- import time import wx from threading import Thread from wx. ...
- Webform--LinQ 分页组合查询
一.linq高级查 1.模糊查(字符串包含) public List<User> Select(string name) { return con.User.Where(r => r ...
- ArcGis汇总篇
ArcGis-javascript-API下载 bigemap.太乐地图 可下载地图文件 用arcgis for js 可以河流流域水质图 ArcGis导出shp文件(dbf.prj.sbn.sbx. ...
- 第29月第27天 Error: Multiple commands produce
1. 解决方法可以有两种,一种是不使用New Build System,在File > Project/Workspace Settings中的Share Project/Workspace S ...