python学习笔记-多进程
multiprocessing
from multiprocessing import Process
import time
def f(name):
time.sleep(2)
print('hello',name) if __name__ == '__main__':
p1 = Process(target=f,args = ('bob',))
p2 = Process(target=f,args=('john',))
p1.start()
p2.start()
p1.join()
显示进程ID
# !/usr/bin/env python
# -*- coding:utf-8 -*- from multiprocessing import Process
import os def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid()) # 父进程ID
print('process id:', os.getpid()) #自己的进程ID
print("\n\n") def f(name):
info('\033[31;1mfunction f\033[0m')
print('hello', name) if __name__ == '__main__':
info('\033[32;1mmain process line\033[0m')
p = Process(target=info, args=('bob',))
p.start()
p.join()
进程间通讯
不同进程间内存是不共享的,要想实现两个进程间的数据交换,可以用以下方法:
Queues
# !/usr/bin/env python
# -*- coding:utf-8 -*-
from multiprocessing import Process, Queue def f(q):
q.put([42, None, 'hello']) if __name__ == '__main__':
q = Queue() #创建队列
p = Process(target=f, args=(q,))
p2 = Process(target=f, args=(q,))
p.start()
p2.start()
print('from parent',q.get()) #获取子进程put的值
print('from parent',q.get())
p.join()
Pipes
The Pipe() function returns a pair of connection objects connected by a pipe which by default is duplex (two-way).
# !/usr/bin/env python
# -*- coding:utf-8 -*- from multiprocessing import Process, Pipe def f(conn):
conn.send([42, None, 'hello']) #发送数据
conn.close() if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p2 = Process(target=f, args=(child_conn,))
p.start()
p2.start()
print(parent_conn.recv()) # 接受数据
print(parent_conn.recv())
p.join()
Managers
A manager object returned by Manager() controls a server process which holds Python objects and allows other processes to manipulate them using proxies.
A manager returned by Manager() will support types list, dict, Namespace, Lock, RLock, Semaphore, BoundedSemaphore, Condition, Event, Barrier, Queue, Value and Array.
# !/usr/bin/env python
# -*- coding:utf-8 -*-
from multiprocessing import Process, Manager def f(d, l):
d[1] = ''
d[''] = 2
d[0.25] = None
l.append(1)
print(l) if __name__ == '__main__':
with Manager() as manager:
d = manager.dict()
l = manager.list(range(5))
p_list = []
for i in range(10):
p = Process(target=f, args=(d, l))
p.start()
p_list.append(p)
for res in p_list:
res.join() print(d)
print(l)
进程同步
Without using the lock output from the different processes is liable to get all mixed up.
from multiprocessing import Process, Lock def f(l, i):
l.acquire()
try:
print('hello world', i)
finally:
l.release() if __name__ == '__main__':
lock = Lock() for num in range(10):
Process(target=f, args=(lock, num)).start()
进程池
进程池内部维护一个进程序列,当使用时,则去进程池中获取一个进程,如果进程池序列中没有可供使用的进进程,那么程序就会等待,直到进程池中有可用进程为止。
进程池中有两个方法:
- apply
- apply_async
from multiprocessing import Process,Pool,freeze_support
import time def Foo(i):
time.sleep(4)
print('exec...')
return i+100 def Bar(arg):
print('-->exec done:',arg) if __name__ == '__main__':
freeze_support()
pool = Pool(5)
for i in range(100):
pool.apply_async(func=Foo, args=(i,),callback=Bar)
#pool.apply(func=Foo, args=(i,))
print('end')
pool.close()
pool.join()
#pool.join()#进程池中进程执行完毕后再关闭,如果注释,那么程序直接关闭。
python学习笔记-多进程的更多相关文章
- Python 学习笔记 多进程 multiprocessing--转载
本文链接地址 http://quqiuzhu.com/2016/python-multiprocessing/ Python 解释器有一个全局解释器锁(PIL),导致每个 Python 进程中最多同时 ...
- python 学习笔记 多进程
要让python程序实现多进程,我们先了解操作系统的相关知识 Unix/Linux操作系统提供了一个fork()系统调用,他非常特殊,普通的函数调用,调用一次,返回一次,但是fork调用一次, 返回两 ...
- python学习笔记——多进程中的锁Lock
1 进程锁 python编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性. 每个对象都对应于一个可称为“互斥锁”的标记,这个标记用来保证在任一时刻,只能有一线程访问对象. 在python中我 ...
- python学习笔记——多进程中共享内存Value & Array
1 共享内存 基本特点: (1)共享内存是一种最为高效的进程间通信方式,进程可以直接读写内存,而不需要任何数据的拷贝. (2)为了在多个进程间交换信息,内核专门留出了一块内存区,可以由需要访问的进程将 ...
- python学习笔记—— 多进程中的 孤儿进程和僵尸进程
1 基本概述 1.1 孤儿进程和僵尸进程 父进程创建子进程后,较为理想状态是子进程结束,父进程回收子进程并释放子进程占有的资源:而实际上,父子进程是异步过程,两者谁先结束是无顺的,一般可以通过父进程调 ...
- python学习笔记——多进程二 进程的退出
1 进程的退出函数的基础语法 1.1 进程的退出函数 进程的退出含有有os._exit([status])和sys.exit([status])两种,从数据包来看,该退出模块仅在linux或者unix ...
- python学习笔记——多进程一 基础概念
1 进程 进程:程序的一次(从开始到结束)执行过程,属于一个动态过程.是系统进行资源分配和调度的基本单位. 程序:指的是一个文件,磁盘中可执行的代码.属于一个静态文件 注:进程运行时需要把程序加载如内 ...
- Python学习笔记进阶篇——总览
Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(Socket编程进阶&多线程.多进程) Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(异常处理) Pyth ...
- python学习笔记整理——字典
python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...
随机推荐
- 在SQL SERVER中根据某字段分隔符将记录分成多条记录
XT_RSGL_KQSZ_LS表结构如下图: CREATE TABLE XT_RSGL_KQSZ_LS( KQFW VARCHAR(400) ) 其中KQFW字段以分割符 , 隔开 INSERT I ...
- background-size拉伸背景图片
在制作页面中常需要对背景图片在容器中进行平铺,可用background-size属性对背景编辑:拉伸,压缩等~ background-size:contain; 将背景扩展到整个容器大小. 较为实用的 ...
- 使用es6的set和map实现数组去重复
var set = new Set();var arr = [1, 2, 3, 3, 2, 1];arr.map(val => set.add(val));// arr.map(function ...
- Ninject之旅之九:Ninject上下文绑定(附程序下载)
摘要 既然在插件模型里,每一个服务类型可以被映射到多个实现,绑定方法不用决定要返回哪个实现.因为kernel应该返回所有的实现.然而,上下文绑定是多个绑定场景,在这个场景里,kernel需要根据给定的 ...
- 萌萌的websocket原理解析
转载自:http://www.zhihu.com/question/20215561 一.WebSocket是HTML5出的东西(协议),也就是说HTTP协议没有变化,或者说没关系,但HTTP是不支持 ...
- iOS 6.0之后支持一个页面横屏的方法
拿两个页面举例子: 0.开启旋转: 1.第一个界面实现以下方法 /** * 默认显示的方向,preferredInterfaceOrientationForPresentation必须返回一个支持的接 ...
- canvas知识点
看到网上某些特别好看的效果,就突然想看看这个canvas; canvas是html5中的一个标签.所以兼容的是Internet Explorer 9.Firefox.Opera.Chrome 和 Sa ...
- asp.net core获取HttpContext相关操作
建立类: using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;us ...
- XML.04-dom4j和XPath
body,td { font-family: calibri; font-size: 10pt } XML.04-dom4j和XPath dom4j的基本使用 XPath 啥是XPath XPath语 ...
- 项目在build machine中失败,本地Build成功的程序集版本问题
MSBuild在build machine中遇到which has a higher version than its reference assembly:(in my case let's say ...