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. 返 ...
随机推荐
- <iframe>标签自适应高度和宽度
<iframe src="index.html" id="iframepage" frameborder="0" scrolling= ...
- Spark Streaming架构设计和运行机制总结
本期内容 : Spark Streaming中的架构设计和运行机制 Spark Streaming深度思考 Spark Streaming的本质就是在RDD基础之上加上Time ,由Time不断的运行 ...
- CACTI表结构和数据被动获取
cacti我们也用了很久了,但是它的表结构一直都没有去关心过,得空抽了半个晚上的时间,把它的库表结构大概看了下,某些字段的含义跟大家分享下:cacti的数据都是存放在rrdtool中的,数据库存放的其 ...
- Session操作
存储API localStorage和sessionStorage通常被当做普通的JavaScript对象使用:通过设置属性来存储字符串值,查询该属性来读取该值.除此之外,这两个对象还提供了更加正式的 ...
- performSelector和respondsToSelector用法
一.performSelector调用和直接调用区别 下面两段代码都在主线程中运行,我们在看别人代码时会发现有时会直接调用,有时会利用performSelector调用,今天看到有人在问这个问题,我便 ...
- mybatis - resultMap
resultMap有比较强大的自动映射,下面是摘自mybatis中文官网的的片段: 当自动映射查询结果时,MyBatis会获取sql返回的列名并在java类中查找相同名字的属性(忽略大小写). 这意味 ...
- modelsim(3) - summary ,issue,tips
1) the OEM of modelsim is 10 times slower than offical questa 2)how to the file full path in the mod ...
- jQuery iframe之间相互调用
,子iframe内调用父类函数方法: window.parent.func(); ,子Iframe中获取父界面的元素: $("#xx", window.parent.documen ...
- git和github
GIT是一款分布式版本控制系统.与SVN相比可以不依赖网络,并且对分支和合并有更好的支持.但是命令稍微复杂一些,这里简单介绍使用git将项目上传到github. 首先GIT安装只需要去官网下载安装即可 ...
- 关于设置anroid系统时间
我最近在做一个项目需要设置android系统时间,设置android 时间往往缺少权限,看到http://blog.csdn.net/kakaxi1o1/article/details/3687278 ...