python10
一、多进程multiprocessing
multiprocessing包是Python中的多进程管理包。与threading.Thread类似,它可以利用multiprocessing.Process对象来创建一个进程。该Process对象与Thread对象的用法相同,也有start(), run(), join()的方法。

1 import multiprocessing,threading
2 import time
3
4 def thread_run():
5 print(threading.get_ident())
6 def run(name):
7 time.sleep(2)
8 print('Hello ',name)
9 t = threading.Thread(target=thread_run)
10 t.start()
11
12
13 if __name__== '__main__':
14 for i in range(10):
15 p = multiprocessing.Process(target=run, args=('bob_%s'%i,))
16 p.start()

运行结果:

1 Hello bob_0
2 1144
3 Hello bob_8
4 1268
5 Hello bob_4
6 4360
7 Hello bob_2
8 768
9 Hello bob_6
10 5308
11 Hello bob_5
12 Hello bob_1
13 6076
14 5088
15 Hello bob_9
16 6104
17 Hello bob_3
18 5196
19 Hello bob_7
20 748

二、进程池
如果要创建多个进程,可以使用进程池,启用进程池需要使用Pool库,使用指令pool=Pool()可自动调用所有CPU,
map()函数相当于一个循环,将参数2中的列表元素逐次灌入参数1的函数中。

1 from multiprocessing import Pool
2
3 def squre(num):
4 return num ** 2
5
6
7 if __name__ == '__main__':
8 numbers = [0,1,2,3,4,5]
9 pool = Pool(processes=5)#进程池中最多能放入5个进程
10 print(pool.map(squre,numbers))

运行结果:
[0, 1, 4, 9, 16, 25]
Pool还有以下常用的方法:
- apply_async(func, args)从进程池中取出一个进程执行func,args为func的参数。它将返回一个AsyncResult的对象,我们可以调用get()方法以获得结果。
- close() 关闭进程池,不再创建新的进程
- join() wait()进程池中的全部进程。但是必须对Pool先调用close()方法才能join.

1 from multiprocessing import Process, Pool,freeze_support
2 import time
3 import os
4
5 def Foo(i):
6 time.sleep(2)
7 print("in process",os.getpid())
8 return i + 100
9
10 def Bar(arg):
11 print('-->exec done:', arg,os.getpid())
12
13 if __name__ == '__main__':
14 #freeze_support()
15 pool = Pool(processes=3)
16 print("主进程",os.getpid())
17 for i in range(10):
18 pool.apply_async(func=Foo, args=(i,), callback=Bar) #callback=回调
19
20 print('end')
21 pool.close()
22 pool.join()

运行结果:

1 主进程 5660
2 end
3 in process 7048
4 -->exec done: 100 5660
5 in process 3396
6 -->exec done: 101 5660
7 in process 6728
8 -->exec done: 102 5660
9 in process 7048
10 -->exec done: 103 5660
11 in process 3396
12 -->exec done: 104 5660
13 in process 6728
14 -->exec done: 105 5660
15 in process 7048
16 -->exec done: 106 5660
17 in process 3396
18 -->exec done: 107 5660
19 in process 6728
20 -->exec done: 108 5660
21 in process 7048
22 -->exec done: 109 5660

除了主进程,其它结果是三个一组执行的,因为进程池中每次最多有三个进程。
三、进程通信
进程间通信常用两种方法:Queue和pipe,Queue可以用在多个进程间实现通信,pipe用在两个进程间通信。

1 import os
2 import multiprocessing
3 import time
4 #==================
5 # input worker
6 def inputQ(queue):
7 info = str(os.getpid()) + '(put):' + str(time.time())
8 queue.put(info)
9
10 # output worker
11 def outputQ(queue,lock):
12 info = queue.get()
13 lock.acquire()
14 print (str(os.getpid()) + '(get):' + info)
15 lock.release()
16
17 if __name__ == '__main__':
18 record1 = [] # store input processes
19 record2 = [] # store output processes
20 lock = multiprocessing.Lock() # To prevent messy print
21 queue = multiprocessing.Queue(3)
22
23
24 for i in range(10):
25 process = multiprocessing.Process(target=inputQ, args=(queue,))
26 process.start()
27 record1.append(process)
28
29
30 for i in range(10):
31 process = multiprocessing.Process(target=outputQ, args=(queue, lock))
32 process.start()
33 record2.append(process)
34
35 for p in record1:
36 p.join()
37
38 queue.close()
39
40 for p in record2:
41 p.join()

运行结果:

1 4004(get):4556(put):1476337412.4875286
2 512(get):5088(put):1476337412.6345284
3 8828(get):7828(put):1476337412.7965286
4 8372(get):1032(put):1476337412.8185284
5 7740(get):1496(put):1476337412.9205284
6 4176(get):632(put):1476337412.9855285
7 5828(get):8508(put):1476337412.9595284
8 4236(get):9204(put):1476337412.9925284
9 7632(get):8956(put):1476337413.2055285
10 6376(get):4160(put):1476337413.0705285

Pipe可以是单向(half-duplex),也可以是双向(duplex)。我们通过mutiprocessing.Pipe(duplex=False)创建单向管道 (默认为双向)。一个进程从PIPE一端输入对象,然后被PIPE另一端的进程接收,单向管道只允许管道一端的进程输入,而双向管道则允许从两端输入。

1 from multiprocessing import Process, Pipe
2
3
4 def f(conn):
5 conn.send([42, None, 'hello from child'])
6 conn.send([42, None, 'hello from child2'])
7 print("from parent:",conn.recv())
8 conn.close()
9
10 if __name__ == '__main__':
11 parent_conn, child_conn = Pipe()
12 p = Process(target=f, args=(child_conn,))
13 p.start()
14 print(parent_conn.recv()) # prints "[42, None, 'hello']"
15 print(parent_conn.recv()) # prints "[42, None, 'hello']"
16 parent_conn.send("chupi可好") # prints "[42, None, 'hello']"
17 p.join()

运行结果:
1 [42, None, 'hello from child']
2 [42, None, 'hello from child2']
3 from parent: chupi可好
python10的更多相关文章
- Python10行以内代码能有什么高端操作
Python10行以内代码能有什么高端操作 Python凭借其简洁的代码,赢得了许多开发者的喜爱.因此也就促使了更多开发者用Python开发新的模块,从而形成良性循环,Python可以凭借更加简短的代 ...
- python10作业思路及源码:类Fabric主机管理程序开发(仅供参考)
类Fabric主机管理程序开发 一,作业要求 1, 运行程序列出主机组或者主机列表(已完成) 2,选择指定主机或主机组(已完成) 3,选择主机或主机组传送文件(上传/下载)(已完成) 4,充分使用多线 ...
- Python-10 字典
#1 创建 dict1={'欢欢':'i love','小高高':'you'} dict2={1:'one',2:'two',3:'three'} dict3={} #2 访问元素 print('欢欢 ...
- Python-10 字典dict
#1 创建 dict1={'欢欢':'i love','小高高':'you'} dict2={1:'one',2:'two',3:'three'} dict3={} #2 访问元素 print('欢欢 ...
- Python-10行代码实现3个数据可视化
阅读本文约“1分钟” 最近将Python作为第二编程语言,进行了了解与学习,可以说它的包是很强大的.这次的demo仅仅不到10行代码就可以实现三个数据可视化的小实例. 我们将要使用到matplotli ...
- 饮冰三年-人工智能-Python-10之C#与Python的对比
1:注释 C# 中 单行注释:// 多行注释:/**/ python 中 单行注释:# 多行注释:“““内容””” 2:字符串 C#中 "" 用双引号如("我是字符串&q ...
- Python10/24--组合/封装/property装饰器/多态
组合的应用: 1. 什么是组合 一个对象的属性是来自于另外一个类的对象,称之为组合 2. 为何用组合 组合也是用来解决类与类代码冗余的问题 3. 如何用组合 '''class Foo: aaa=111 ...
- Python10/23--继承/派生
(继承)1. 什么是继承? 在程序中继承是一种新建子类的方式,新创建的类称之为子类\派生类,被继承的类称之为父类\基类\超类 继承描述的是一种遗传关系,子类可以重用父类的属性 2. 为何用继承? 减少 ...
- Python10/22--面向对象编程/类与对象/init函数
类: 语法: class关键字 类名# 类名规范 大写开头 驼峰命名法class SHOldboyStudent: # 描述该类对象的特征 school = "上海Oldboy" ...
- Python10/17-re模块/hashlib模块/logging模块
import logging # 1.日志的级别# logging.debug("这是一个调试信息") # 10# logging.info("常规信息") # ...
随机推荐
- python中那些让开发事半功倍的模块
1. Map Map会将一个函数映射到一个输入列表的所有元素上 ex: 有一个列表: [1,2,3,4,5,6], 现在要求把列表每个元素乘以10 如果你还不知道Map,那你可能会这样做: list1 ...
- 微信小程序开发(二)认识开发工具
腾讯微信团队提供非常优秀的微信小程序开发工具,大大降低了开发者的入门门槛,为他们点赞!上一篇文章已经说明了,如何注册及下载开发工具,现在我们就来一起认识见识一下开发工具的庐山真面目. 首次打开这个开发 ...
- 给 ABP vNext 应用安装私信模块
在上一节五分钟完成 ABP vNext 通讯录 App 开发 中,我们用完成了通讯录 App 的基础开发. 这本章节,我们会给通讯录 App 安装私信模块,使不同用户能够通过相互发送消息,并接收新私信 ...
- CVE-20117-111882漏洞复现及利用
背景 工程实践题目: 渗透方向:实验班要求 1.利用已有的漏洞,搭建内网实验环境(WEB漏洞或系统漏洞以近两年内的CVE编号为准,每人一个,先报先得,具体由学习委员负责协调),利用工具进行内网渗透攻击 ...
- docker redis安装及配置(外网访问 关闭安全限制 设置密码)
docker run -p 6379:6379 --name redis -v /usr/local/redis/etc/redis.conf:/etc/redis/redis.conf -v /us ...
- Kubernetes实战总结 - 系统初始化
设置系统主机名以及Host文件的相互解析 hostnamectl set-hostname k8s-master01 cat >> /etc/hosts <<EOF 192.1 ...
- 当程序执行一条查询语句时,MySQL内部到底发生了什么? (说一下 MySQL 执行一条查询语句的内部执行过程?
先来个最基本的总结阐述,希望各位小伙伴认真的读一下,哈哈: 1)客户端(运行程序)先通过连接器连接到MySql服务器. 2)连接器通过数据库权限身份验证后,会先查询数据库缓存是否存在(之前执行过相同条 ...
- [线段树]Codeforces 339D Xenia and Bit Operations
Xenia and Bit Operations time limit per test 2 seconds memory limit per test 256 megabytes input sta ...
- 检测页面是否允许使用Flash
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- PHP - json_decode returns NULL的解决办法
碰到了PHP json_decode returns NULL, 肿么办? 1. google 一下, 关键字:PHP json_decode NULL 首先你能看到我这个这个帖子:) http:// ...