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. 返 ...
随机推荐
- 二模12day2解题报告
T1.笨笨玩糖果(sugar) 有n颗糖,两个人轮流取质数颗糖,先取不了的(0或1)为输,求先手能否必胜,能,输出最少几步肯定能赢:不能,输出-1. 一开始天真的写了一个dp,f[i]表示i颗糖最少取 ...
- Linux常见疑难问答
Linux常见疑难问答 (1)按a~z顺序排列启动服务进程. #exportLC_ALL=C #英文环境变量设置,主要用于解决乱码问题 #chkconfig –list | gre ...
- neutron debug
neutron port-list neutron port-delete neutron floatingip-list neutron floatingip-delete
- js back动作
history.back(-1):直接返回当前页的上一页,数据全部消息,是个新页面 history.go(-1):也是返回当前页的上一页,不过表单里的数据全部还在 history.back(0) 刷新 ...
- MySQL学习(一)
mysql left join,right join,inner join用法分析 left join:是以A表的记录为基础的,A可以看成左表,B可以看成右表,left join是以左表为准的. 换句 ...
- YCSB测试Mysql,MongoDB,TokuMX,Couchbase性能
测试是由同事完成的,这里只做收藏. 测试说明: 1.数据量为3kw记录,每条记录11个字段,一个为主键,主键为字符类型,类似:user****,后续为数值 其他10字段为字符类型,100字符,记录长度 ...
- ue4框架C++语法汇总文章
1.Run external .exe file TCHAR* url = TEXT("C:\\windows\\system32\\calc.exe"); FPlatformPr ...
- Nginx配置文件说明
在此记录下Nginx服务器nginx.conf的配置文件说明, 部分注释: #运行用户user www-data; #启动进程,通常设置成和cpu的数量相等worker_processes 1 ...
- 『c++』 模板(template)--- 参数化多态性
---恢复内容开始--- 题外话: 模板机制的设计和细节是由Bjarne Stroustrup在其1988年10月发表的名为“Parameterized Types for C++”一文中披露的. 引 ...
- js关于页面坐标api
网页可见区域宽: document.body.clientWidth;网页可见区域高: document.body.clientHeight;网页可见区域宽: document.body.offset ...