python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU资源,在python中大部分情况需要使用多进程。python提供了非常好用的多进程包Multiprocessing,只需要定义一个函数,python会完成其它所有事情。借助这个包,可以轻松完成从单进程到并发执行的转换。multiprocessing支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、LocK等组件

一、Process

语法:Process([group[,target[,name[,args[,kwargs]]]]])

参数含义:target表示调用对象;args表示调用对象的位置参数元祖;kwargs表示调用对象的字典。name为别名,groups实际上不会调用。

方法:is_alive():

   join(timeout):

   run():

   start():

   terminate():

属性:authkey、daemon(要通过start()设置)、exitcode(进程在运行时为None、如果为-N,表示被信号N结束)、name、pid。其中daemon是父进程终止后自动终止,且自己不能产生新的进程,必须在start()之前设置。

1.创建函数,并将其作为单个进程

from multiprocessing import Process
def func(name):
print("%s曾经是好人"%name) if __name__ == "__main__":
p = Process(target=func,args=('kebi',))
p.start() #start()通知系统开启这个进程

2.创建函数并将其作为多个进程

from multiprocessing import Process
import random,time def hobby_motion(name):
print('%s喜欢运动'% name)
time.sleep(random.randint(1,3)) def hobby_game(name):
print('%s喜欢游戏'% name)
time.sleep(random.randint(1,3)) if __name__ == "__main__":
p1 = Process(target=hobby_motion,args=('付婷婷',))
p2 = Process(target=hobby_game,args=('科比',))
p1.start()
p2.start()

执行结果:

付婷婷喜欢运动
科比喜欢游戏

3.将进程定义为类(开启进程的另一种方法,并不是很常用)

from multiprocessing import Process
class MyProcess(Process):
def __init__(self,name):
super().__init__()
self.name = name def run(self): #start()时,run自动调用,而且此处只能定义为run。
print("%s曾经是好人"%self.name) if __name__ == "__main__":
p = MyProcess('kebi')
p.start() #将Process当作父类,并且自定义一个函数。

4.daemon程序对比效果

不加daemon属性

import time
def func(name):
print("work start:%s"% time.ctime())
time.sleep(2)
print("work end:%s"% time.ctime()) if __name__ == "__main__":
p = Process(target=func,args=('kebi',))
p.start()
print("this is over") #执行结果
this is over
work start:Thu Nov 30 16:12:00 2017
work end:Thu Nov 30 16:12:02 2017

加上daemon属性

from multiprocessing import Process
import time
def func(name):
print("work start:%s"% time.ctime())
time.sleep(2)
print("work end:%s"% time.ctime()) if __name__ == "__main__":
p = Process(target=func,args=('kebi',))
p.daemon = True #父进程终止后自动终止,不能产生新进程,必须在start()之前设置
p.start()
print("this is over") #执行结果
this is over

设置了daemon属性又想执行完的方法:

import time
def func(name):
print("work start:%s"% time.ctime())
time.sleep(2)
print("work end:%s"% time.ctime()) if __name__ == "__main__":
p = Process(target=func,args=('kebi',))
p.daemon = True
p.start()
p.join() #执行完前面的代码再执行后面的
print("this is over") #执行结果
work start:Thu Nov 30 16:18:39 2017
work end:Thu Nov 30 16:18:41 2017
this is over

5.join():上面的代码执行完毕之后,才会执行后i面的代码。

先看一个例子:

from multiprocessing import Process
import time,os,random
def func(name,hour):
print("A lifelong friend:%s,%s"% (name,os.getpid()))
time.sleep(hour)
print("Good bother:%s"%name) if __name__ == "__main__":
p = Process(target=func,args=('kebi',2))
p1 = Process(target=func,args=('maoxian',1))
p2 = Process(target=func,args=('xiaoniao',3))
p.start()
p1.start()
p2.start()
print("this is over") 执行结果:
this is over #最后执行,最先打印,说明start()只是开启进程,并不是说一定要执行完
A lifelong friend:kebi,12048
A lifelong friend:maoxian,8252
A lifelong friend:xiaoniao,6068
Good bother:maoxian #最先打印,第二位执行
Good bother:kebi
Good bother:xiaoniao

添加join()

from multiprocessing import Process
import time,os,random
def func(name,hour):
print("A lifelong friend:%s,%s"% (name,os.getpid()))
time.sleep(hour)
print("Good bother:%s"%name)
start = time.time()
if __name__ == "__main__":
p = Process(target=func,args=('kebi',2))
p1 = Process(target=func,args=('maoxian',1))
p2 = Process(target=func,args=('xiaoniao',3))
p.start()
p.join() #上面的代码执行完毕之后,再执行后面的
p1.start()
p1.join()
p2.start()
p2.join()
print("this is over")
print(time.time() - start) #执行结果
A lifelong friend:kebi,14804
Good bother:kebi
A lifelong friend:maoxian,11120
Good bother:maoxian
A lifelong friend:xiaoniao,10252 #每个进程执行完了,才会执行下一个
Good bother:xiaoniao
this is over
6.497815370559692 #2+1+3+主程序执行时间

改变一下位置

from multiprocessing import Process
import time,os,random
def func(name,hour):
print("A lifelong friend:%s,%s"% (name,os.getpid()))
time.sleep(hour)
print("Good bother:%s"%name)
start = time.time()
if __name__ == "__main__":
p = Process(target=func,args=('kebi',2))
p1 = Process(target=func,args=('maoxian',1))
p2 = Process(target=func,args=('xiaoniao',3))
p.start()
p1.start()
p2.start()
p.join() #需要2秒
p1.join() #到这时已经执行完
p2.join() #已经执行了2秒,还要1秒
print("this is over")
print(time.time() - start) #执行结果 A lifelong friend:kebi,13520
A lifelong friend:maoxian,11612
A lifelong friend:xiaoniao,17064 #几乎是同时开启执行
Good bother:maoxian
Good bother:kebi
Good bother:xiaoniao
this is over
3.273620367050171 #以最长时间的为主

6.其它属性和方法

from multiprocessing import Process
import time
def func(name):
print("work start:%s"% time.ctime())
time.sleep(2)
print("work end:%s"% time.ctime()) if __name__ == "__main__":
p = Process(target=func,args=('kebi',))
p.start()
p.terminate() #将进程杀死,而且必须放在start()后面,与daemon的功能类似 #执行结果
this is over
from multiprocessing import Process
import time
def func(name):
print("work start:%s"% time.ctime())
time.sleep(2)
print("work end:%s"% time.ctime()) if __name__ == "__main__":
p = Process(target=func,args=('kebi',))
# p.daemon = True
print(p.is_alive())
p.start()
print(p.name) #获取进程的名字
print(p.pid) #获取进程的pid
print(p.is_alive()) #判断进程是否存在
print("this is over")

python多进程编程常用到的方法的更多相关文章

  1. Python 多进程编程之 进程间的通信(Queue)

    Python 多进程编程之 进程间的通信(Queue) 1,进程间通信Process有时是需要通信的,操作系统提供了很多机制来实现进程之间的通信,而Queue就是其中的一个方法----这是操作系统开辟 ...

  2. Python多进程编程

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

  3. 【转】Python多进程编程

    [转]Python多进程编程 序. multiprocessingpython中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程.Pytho ...

  4. Python 多进程编程之 进程间的通信(在Pool中Queue)

    Python 多进程编程之 进程间的通信(在Pool中Queue) 1,在进程池中进程间的通信,原理与普通进程之间一样,只是引用的方法不同,python对进程池通信有专用的方法 在Manager()中 ...

  5. 深入理解python多进程编程

    1.python多进程编程背景 python中的多进程最大的好处就是充分利用多核cpu的资源,不像python中的多线程,受制于GIL的限制,从而只能进行cpu分配,在python的多进程中,适合于所 ...

  6. Python爬虫beautifulsoup4常用的解析方法总结(新手必看)

    今天小编就为大家分享一篇关于Python爬虫beautifulsoup4常用的解析方法总结,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧摘要 如何用beau ...

  7. Java && Python 算法面试常用类以及方法总结

    数据结构 逻辑结构上: 包括集合,线性结构,非线性结构. 存储结构: 顺序存储,链式存储,索引存储,散列存储. Java 常见数据结构 大专栏  Java && Python 算法面试 ...

  8. Python编程-常用模块及方法

    常用模块介绍 一.time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行 ...

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

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

随机推荐

  1. iphone开发-SQLite数据库使用

    我现在要使用SQLite3.0创建一个数据库,然后在数据库中创建一个表格. 首先要引入SQLite3.0的lib库.然后包含头文件#import <sqlite3.h> [1]打开数据库, ...

  2. FTP的主动模式与被动模式

    FTP服务器使用20和21两个网络端口与FTP客户端进行通信. FTP服务器的21端口用于传输FTP的控制命令,20端口用于传输文件数据. FTP主动模式: FTP客户端向服务器的FTP控制端口(默认 ...

  3. 转:GRADLE构建最佳实践

    转自: http://www.figotan.org/2016/04/01/gradle-on-android-best-practise/#section-2 随着谷歌对Eclipse的无情抛弃和对 ...

  4. 19. Spring Boot 添加JSP支持【从零开始学Spring Boot】

    转:http://blog.csdn.net/linxingliang/article/details/52017140 这个部分比较复杂,所以单独创建一个工程来进行讲解: 大体步骤: (1)     ...

  5. Kali Linux 2.0安装光盘分享

    Kali Linux 2.0安装光盘分享 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I ...

  6. 模拟IE各种版本的方法

    下载360极速浏览器.开启“兼容模式” 默认会是IE7.可以通过控制台(Ctrl + shift + I)调整各个版本

  7. Shell脚本笔记 1

    函数别名 设置别名 alias name="command" alias ll="ls -laS" 取消别名 unalias name 求取数学表达式 valu ...

  8. asp.net core 系列之Reponse caching之cache in-memory (2)

    这篇文章(主要翻译于官网,水平有限,见谅)讲解asp.net core 中的 Cache in-memory (内存缓存). Cache in-memory in ASP.NET Core Cachi ...

  9. NUTCH2.3 hadoop2.7.1 hbase1.0.1.1 solr5.2.1部署(二)

     Precondition: hadoop 2.7.1 hbase 1.0.1.1 / hbase 0.98.13 192.168.1.106 ->master 192.168.1.105 ...

  10. Emgu安装配置及使用

    前言:项目需要,需使用图像处理来完成机械臂从运动的皮带上抓取物体的功能,所以又重拾视觉与图像处理内容. 内容:Emgu是OpenCV的一个跨平台的.NET封装,结构如下图所示: 下载地址:http:/ ...