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 多进程概述的更多相关文章

  1. Python多进程编程

    转自:Python多进程编程 阅读目录 1. Process 2. Lock 3. Semaphore 4. Event 5. Queue 6. Pipe 7. Pool 序. multiproces ...

  2. Python多进程(1)——subprocess与Popen()

    Python多进程方面涉及的模块主要包括: subprocess:可以在当前程序中执行其他程序或命令: mmap:提供一种基于内存的进程间通信机制: multiprocessing:提供支持多处理器技 ...

  3. Python多进程使用

    [Python之旅]第六篇(六):Python多进程使用   香飘叶子 2016-05-10 10:57:50 浏览190 评论0 python 多进程 多进程通信 摘要:   关于进程与线程的对比, ...

  4. python多进程断点续传分片下载器

    python多进程断点续传分片下载器 标签:python 下载器 多进程 因为爬虫要用到下载器,但是直接用urllib下载很慢,所以找了很久终于找到一个让我欣喜的下载器.他能够断点续传分片下载,极大提 ...

  5. Python多进程multiprocessing使用示例

    mutilprocess简介 像线程一样管理进程,这个是mutilprocess的核心,他与threading很是相像,对多核CPU的利用率会比threading好的多. import multipr ...

  6. Python多进程并发(multiprocessing)用法实例详解

    http://www.jb51.net/article/67116.htm 本文实例讲述了Python多进程并发(multiprocessing)用法.分享给大家供大家参考.具体分析如下: 由于Pyt ...

  7. python 多进程开发与多线程开发

    转自: http://tchuairen.blog.51cto.com/3848118/1720965 博文作者参考的博文:  博文1  博文2 我们先来了解什么是进程? 程序并不能单独运行,只有将程 ...

  8. Python多进程----从入门到放弃

    Python多进程 (所有只写如何起多进程跑数据,多进程数据汇总处理不提的都是耍流氓,恩,就这么任性) (1)进程间数据问题,因为多进程是完全copy出的子进程,具有独立的单元,数据存储就是问题了 ( ...

  9. day-4 python多进程编程知识点汇总

    1. python多进程简介 由于Python设计的限制(我说的是咱们常用的CPython).最多只能用满1个CPU核心.Python提供了非常好用的多进程包multiprocessing,他提供了一 ...

随机推荐

  1. Windows下安装Redis数据库并实现C#访问

    1.Redis在Windows下的安装 目前Redis官方并不支持Redis的Windows版本,需要去GitHub下载. GitHub上的Redis分两种,一种是以命令行形式安装的,一种是以Wind ...

  2. Java版本

    Java版本 Java版本分为J2SE(Java 2 Standard Edition,Java标准版).J2ME(Java 2 Micro Edition,Java微型版本)和J2EE(Java 2 ...

  3. mac上搭建appium环境过程以及遇到的问题

    Mac环境安装appium 一.Java环境 下载java sdk http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downl ...

  4. 又见Bug

    文章转载自「开发者圆桌」一个关于开发者入门.进阶.踩坑的微信公众号 作为一名开发者,如何解决遇到的问题.异常或Bug,是开发者必须要面对的,尽管问题很多,情况复杂,但还是有方法和技巧可寻的. 问题无非 ...

  5. 走进 Redis 的世界

    NoSQL(Not Only SQL) 在现今已经应用非常普遍了,尤其是 Redis 和 MongoDB.我们现在来说说 Redis. 前世 Redis 是一个意大利人 Salvatore Sanfi ...

  6. 3408: [Usaco2009 Oct]Heat Wave 热浪

    3408: [Usaco2009 Oct]Heat Wave 热浪 Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 67  Solved: 55[Subm ...

  7. 【故障•监听】TNS-12518、TNS-00517和 Linux Error:32:Broken pipe

    [故障|监听]TNS-12518.TNS-00517和 Linux Error:32:Broken pipe 1.1  BLOG文档结构图 1.2  前言部分 1.2.1  导读和注意事项 各位技术爱 ...

  8. python 使用内置函数sorted对各种数据类型进行排序

    python有两个内置的函数用于实现排序,一个是list.sort()函数,一个是sorted()函数. 区别1:list.sort()函数只能处理list类型数据的排序:sorted()则可以处理多 ...

  9. js应用之实现图片切换效果

    数组的操作与应用 数组的定义 var 数组名=new Array(); //创建空数组 var 数组名=new Array(size);//创建指定数组长度的数组 var 数组名=new Array( ...

  10. 用javascript动态改变网页文字大小

    <script>function setFontSize(size){document.getElementById('bottom').style.fontsize=size+'pt'; ...