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. C51编程中对单片机绝对地址访问的两种方法

    在进行8051单片机应用系统程序设计时,编程都往往少不了要直接操作系统的各个存储器地址空间.C51程序经过编译之后产生的目标代码具有浮动地址,其绝对地址必须经过BL51连接定位后才能确定.为了能够在C ...

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

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

  3. Python多进程编程

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

  4. 【转】Python多进程编程

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

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

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

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

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

  7. 关于python多线程编程中join()和setDaemon()的一点儿探究

    关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的  ...

  8. 服务器文档下载zip格式 SQL Server SQL分页查询 C#过滤html标签 EF 延时加载与死锁 在JS方法中返回多个值的三种方法(转载) IEnumerable,ICollection,IList接口问题 不吹不擂,你想要的Python面试都在这里了【315+道题】 基于mvc三层架构和ajax技术实现最简单的文件上传 事件管理

    服务器文档下载zip格式   刚好这次项目中遇到了这个东西,就来弄一下,挺简单的,但是前台调用的时候弄错了,浪费了大半天的时间,本人也是菜鸟一枚.开始吧.(MVC的) @using Rattan.Co ...

  9. Python中模拟enum枚举类型的5种方法分享

    这篇文章主要介绍了Python中模拟enum枚举类型的5种方法分享,本文直接给出实现代码,需要的朋友可以参考下   以下几种方法来模拟enum:(感觉方法一简单实用) 复制代码代码如下: # way1 ...

随机推荐

  1. 如何去掉Eclipse注释中英文单词的拼写错误检查

  2. java 8时间使用LocalDateTime,ZonedDateTime,LocalDate

    前言 java 8的时间已经能够满足日常的使用,也方便理解.joda-time作为一个有优秀的时间组件也不得不告知使用者在java 8以后使用自带的时间 LocalDateTime以及ZonedDat ...

  3. keil中的一些技巧

    一  在Keil5中使用代码格式化工具Astyle(插件)https://blog.csdn.net/u010160335/article/details/78587411 二 将keil中的内存变量 ...

  4. 学习不一样的Vue1:环境搭建

    学习不一样的Vue1:环境搭建  发表于 2017-05-31 |  分类于 web前端|  |  阅读次数 11677 首先 首发博客: 我的博客 项目源码: 源码 项目预览: 预览 因为个人的喜好 ...

  5. PAT A 1020 Tree Traversals

    给出一棵二叉树的后序遍历序列和中序遍历序列,求这棵二叉树的层序遍历序列 #include<iostream> #include<cstring> #include<que ...

  6. cookie、session、localStorage、sessionStorage的区别

    cookie的机制 cookie是存储在用户本地终端上的数据.有时也用cookies,指某些网站为了辨别用户身份,进行session跟踪而存储在本地终端上的数据,通常经过加密. Cookie是服务器发 ...

  7. redhat 7.6 查看硬件负载命令

    1.  命令 查看CPU负载 命令1:uptime 命令2:cat  /proc/loadavg 查看CPU信息:cat  /proc/cpuinfo load average:表示平均1分钟内运行的 ...

  8. Hibernate(九)--N+1问题

    1.在利用Hibernate操作数据库的时候,如果在实体类上设置了表的双向关联.这可能会出现Hibernate N+1的问题. 1.1.一对多: 在一方,查找得到了 n 个对象,那么又需要将 n 个对 ...

  9. uniGUI之uniPanel(20)

    1]uniPanel常用设置: 2]多个uniPanel在一个uniPanel里显示 uniPanel常用设置: 2]多个uniPanel在一个uniPanel里显示 uniPanel0.Alignm ...

  10. 初识Python和使用Python爬虫

     一.python基础知识了解:   1.特点: Python的语言特性: Python是一门具有强类型(即变量类型是强制要求的).动态性.隐式类型(不需要做变量声明).大小写敏感(var和VAR代表 ...