Python 多进程概述
multiprocessing
python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了非常好用的多进程包multiprocessing,只需要定义一个函数,Python会完成其他所有事情。借助这个包,可以轻松完成从单进程到并发执行的转换。multiprocessing支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。
multiprocessing包是Python中的多进程管理包。与threading.Thread类似,它可以利用multiprocessing.Process对象来创建一个进程。该进程可以运行在Python程序内部编写的函数。该Process对象与Thread对象的用法相同,也有start(), run(), join()的方法。此外multiprocessing包中也有Lock/Event/Semaphore/Condition类 (这些对象可以像多线程那样,通过参数传递给各个进程),用以同步进程,其用法与threading包中的同名类一致。所以,multiprocessing的很大一部份与threading使用同一套API,只不过换到了多进程的情境。
但在使用这些共享API的时候,我们要注意以下几点:
- 在UNIX平台上,当某个进程终结之后,该进程需要被其父进程调用wait,否则进程成为僵尸进程(Zombie)。所以,有必要对每个Process对象调用join()方法 (实际上等同于wait)。对于多线程来说,由于只有一个进程,所以不存在此必要性。
- multiprocessing提供了threading包中没有的IPC(比如Pipe和Queue),效率上更高。应优先考虑Pipe和Queue,避免使用Lock/Event/Semaphore/Condition等同步方式 (因为它们占据的不是用户进程的资源)。
- 多进程应该避免共享资源。在多线程中,我们可以比较容易地共享资源,比如使用全局变量或者传递参数。在多进程情况下,由于每个进程有自己独立的内存空间,以上方法并不合适。此时我们可以通过共享内存和Manager的方法来共享资源。但这样做提高了程序的复杂度,并因为同步的需要而降低了程序的效率。
Process.PID中保存有PID,如果进程还没有start(),则PID为None。
window系统下,需要注意的是要想启动一个子进程,必须加上那句if __name__ == "main",进程相关的要写在这句下面。
1. Process
创建进程的类:
Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。name为别名。group实质上不使用。
方法:is_alive()、join([timeout])、run()、start()、terminate()。其中,Process以start()启动某个进程。
属性:
authkey、daemon(要通过start()设置)
exitcode(进程在运行时为None、如果为–N,表示被信号N结束)
name、pid。其中daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置。
#coding:UTF8 import multiprocessing
import time def worker(interval):
n = 5
while n > 0:
print ("The time is {0}".format(time.ctime()))
time.sleep(1)
n -= 1 if __name__=='__main__':
p = multiprocessing.Process(target=worker,args=(3,))
p.start()
print "p.pid:", p.pid
print "p.name:", p.name
print "p.is_alive:", p.is_alive()
print format(time.ctime())
创建函数并将其作为单个进程
p.pid: 2208
p.name: Process-1
p.is_alive: True
Thu Feb 23 15:31:02 2017
The time is Thu Feb 23 15:31:02 2017
The time is Thu Feb 23 15:31:03 2017
The time is Thu Feb 23 15:31:04 2017
The time is Thu Feb 23 15:31:05 2017
The time is Thu Feb 23 15:31:06 2017
运行结果
#coding:UTF8 import multiprocessing
import time def work1(interval):
print 'work1'
time.sleep(interval)
print 'end_work1' def work2(interval):
print 'work2'
time.sleep(interval)
print 'end_work2' def work3(interval):
print 'work3'
time.sleep(interval)
print 'end_work3' if __name__=="__main__":
p1 = multiprocessing.Process(target=work1,args=(2,))
p2 = multiprocessing.Process(target=work2,args=(2,))
p3 = multiprocessing.Process(target=work3,args=(2,)) p1.start()
p2.start()
p3.start() print ("The number of CPU is:" + str(multiprocessing.cpu_count()))
for p in multiprocessing.active_children():
print ("Child p.name:" + p.name + "\tp.id:" + str(p.pid)) print "END!!!"
创建函数并将其作为多个进程
The number of CPU is:4
Child p.name:Process-1 p.id:7884
Child p.name:Process-3 p.id:5948
Child p.name:Process-2 p.id:4288
END!!!
work1
work2
work3
end_work1
end_work2
end_work3
运行结果
#coding:UTF8 #将进程定义为 类 import multiprocessing
import time class ClockProcess(multiprocessing.Process):
def __init__(self,interval):
multiprocessing.Process.__init__(self)
self.interval = interval def run(self):
n = 5
while n > 0:
print ("The time is {0}".format(time.ctime()))
time.sleep((self.interval))
n -= 1 if __name__=="__main__":
p = ClockProcess(3)
p.start()
将进程定义为类
注:进程p调用start()时,自动调用run()
The time is Thu Feb 23 16:28:56 2017
The time is Thu Feb 23 16:28:59 2017
The time is Thu Feb 23 16:29:02 2017
The time is Thu Feb 23 16:29:05 2017
The time is Thu Feb 23 16:29:08 2017
运行结果
daemon程序对比结果
不加daemon
#coding:UTF8 import multiprocessing
import time def work(interval):
print ("work start:{0}".format(time.ctime()))
time.sleep(interval)
print ("word end:{0}".format(time.ctime())) if __name__=="__main__":
p = multiprocessing.Process(target=work,args = (2,))
p.start()
print "End!!"
不加daemon
End!!
work start:Thu Feb 23 16:36:58 2017
word end:Thu Feb 23 16:37:00 2017
运行结果
#coding:UTF8 import multiprocessing
import time def work(interval):
print ("work start:{0}".format(time.ctime()))
time.sleep(interval)
print ("word end:{0}".format(time.ctime())) if __name__=="__main__":
p = multiprocessing.Process(target=work,args = (2,))
#加上daemon属性
p.daemon = True
p.start()
print "End!!"
加上daemon
End!!
运行结果
注:因子进程设置了daemon属性,主进程结束,它们就随着结束了。
#coding:UTF8 import multiprocessing
import time def work(interval):
print ("work start:{0}".format(time.ctime()))
time.sleep(interval)
print ("word end:{0}".format(time.ctime())) if __name__=="__main__":
p = multiprocessing.Process(target=work,args = (2,))
#加上daemon属性
p.daemon = True
p.start()
p.join() #设置daemon执行完结束的方法
print "End!!"
设置daemon执行完结束的方法
work start:Thu Feb 23 16:38:47 2017
word end:Thu Feb 23 16:38:49 2017
End!!
运行结果
2. Lock
当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突。
#coding:UTF8 import multiprocessing
import sys def Work_With(lock,f):
with lock:
fs = open(f,'a+')
n = 10
while n > 1:
fs.write("Lock acquired via with\n")
n -= 1
fs.close() def Worker_No_With(lock, f):
lock.acquire()
try:
fs = open(f,'a+')
n = 10
while n > 1:
fs.write("Lock acquired directly\n")
n -= 1
fs.close()
finally:
lock.release() if __name__=="__main__":
lock = multiprocessing.Lock()
f = "filetmp.txt"
pw = multiprocessing.Process(target=Work_With, args = (lock,f))
pnw = multiprocessing.Process(target = Worker_No_With,args = (lock,f))
pw.start()
pnw.start()
print "End!!"
End!! 文件内容:filetmp.txt
Lock acquired via with
Lock acquired via with
Lock acquired via with
Lock acquired via with
Lock acquired via with
Lock acquired via with
Lock acquired via with
Lock acquired via with
Lock acquired via with
Lock acquired directly
Lock acquired directly
Lock acquired directly
Lock acquired directly
Lock acquired directly
Lock acquired directly
Lock acquired directly
Lock acquired directly
Lock acquired directly
输出结果
Python 多进程概述的更多相关文章
- Python多进程编程
转自:Python多进程编程 阅读目录 1. Process 2. Lock 3. Semaphore 4. Event 5. Queue 6. Pipe 7. Pool 序. multiproces ...
- Python多进程(1)——subprocess与Popen()
Python多进程方面涉及的模块主要包括: subprocess:可以在当前程序中执行其他程序或命令: mmap:提供一种基于内存的进程间通信机制: multiprocessing:提供支持多处理器技 ...
- Python多进程使用
[Python之旅]第六篇(六):Python多进程使用 香飘叶子 2016-05-10 10:57:50 浏览190 评论0 python 多进程 多进程通信 摘要: 关于进程与线程的对比, ...
- python多进程断点续传分片下载器
python多进程断点续传分片下载器 标签:python 下载器 多进程 因为爬虫要用到下载器,但是直接用urllib下载很慢,所以找了很久终于找到一个让我欣喜的下载器.他能够断点续传分片下载,极大提 ...
- Python多进程multiprocessing使用示例
mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多. import multipr ...
- Python多进程并发(multiprocessing)用法实例详解
http://www.jb51.net/article/67116.htm 本文实例讲述了Python多进程并发(multiprocessing)用法.分享给大家供大家参考.具体分析如下: 由于Pyt ...
- python 多进程开发与多线程开发
转自: http://tchuairen.blog.51cto.com/3848118/1720965 博文作者参考的博文: 博文1 博文2 我们先来了解什么是进程? 程序并不能单独运行,只有将程 ...
- Python多进程----从入门到放弃
Python多进程 (所有只写如何起多进程跑数据,多进程数据汇总处理不提的都是耍流氓,恩,就这么任性) (1)进程间数据问题,因为多进程是完全copy出的子进程,具有独立的单元,数据存储就是问题了 ( ...
- day-4 python多进程编程知识点汇总
1. python多进程简介 由于Python设计的限制(我说的是咱们常用的CPython).最多只能用满1个CPU核心.Python提供了非常好用的多进程包multiprocessing,他提供了一 ...
随机推荐
- 读书笔记 effective c++ Item 23 宁可使用非成员非友元函数函数也不使用成员函数
1. 非成员非友元好还是成员函数好? 想象一个表示web浏览器的类.这样一个类提供了清除下载缓存,清除URL访问历史,从系统中移除所有cookies等接口: class WebBrowser { pu ...
- ABP学习笔记
1. 用 Nhibernate:CountAsync 是定义在System.Data.Entity里的 var totalCount = await query.CountAsync(); 出现以 ...
- SQL SERVER的事务日志
1 基本介绍 每个数据库都具有事务日志,用于记录所有事物以及每个事物对数据库所作的操作. 日志的记录形式需要根据数据库的恢复模式来确定,数据库恢复模式有三种: 完整模式,完全记录事物日志,需要定期进行 ...
- angular drag and drop (marceljuenemann) 笔记
这是原文 http://marceljuenemann.github.io/angular-drag-and-drop-lists/demo/#/simple 看起来很多功能,所以我只记入我需要的部分 ...
- HBase、HDFS和MapReduce架构异同简解
HBase.HDFS和MapReduce架构异同 .. HBase(公司架构模型) HDFS2.0(公司架构模型) MR2.0(公司架构模型) MR1.0(公司架构模型) 中央 HMaster Nam ...
- struts2中Action到底是什么,怎么理解
struts2中Action到底是什么,怎么理解 1.配置完web.xml2.创建视图页面login.jsp3.创建业务控制器LoginAction类(解释说:创建业务控制器LoginAction类, ...
- UIScrollView 和 UICollectionView 分页效果
UIScrollView 和 UICollectionView 分页效果 UIScrollView可以滚动显示宽度或高度大于其bounds的内容.有些时候,需要有分页效果.每一页有统一的大小,相邻无缝 ...
- Macaca 自动化框架 [Python 系列]
介绍 Macaca是一套完整的自动化测试解决方案,基于node.js开发.由阿里巴巴公司开源: 地址:http://macacajs.github.io/macaca/ 特点: 同时支持PC端和移动端 ...
- Spring-boot 最小demo
POM 文件,注意红色部分: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http: ...
- Leetcode_001_TwoSum_求和为固定数的两个数的索引
题目描述 给定一个整型数组,在数组中找出两个数使这两个数的和为给定数,从小到大输出这两个数在数组中的位置(我们可以假定输出结果只有一个).例如,输入:N={1,4,8,20}, target=1 ...