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. eclipse中mybatis generator插件的安装与使用,实现自动生成代码

    git地址:https://github.com/mybatis/generator 下载后解压: 选择任意一个版本的jar放到eclipse的features目录下即可 选择任意一个版本的jar放到 ...

  2. Spark sql读取数据库和ES数据进行处理代码

    读取数据库数据和ElasticSearch数据进行连接处理 import java.util.HashMap; import java.util.List; import java.util.Map; ...

  3. linux中du的用法

    du:Disk Usage的缩写,命令功能为显示目录(或文件)所占磁盘空间的大小. 语 法:du [-abcDhHklmsSx0] [-L][-X File][--block-size=SIZE][- ...

  4. 模拟利器Mockito

    16.3.1  模拟测试概述 目前支持Java语言的Mock测试工具有EasyMock.JMock.Mockito.MockCreator.Mockrunner.MockMaker等,Mockito是 ...

  5. 微信小程序-上传多张图片加进度条(支持预览、删除)

    2018-12-24 详情示例见:https://www.cnblogs.com/cisum/p/9564898.html 2018-12-29 组件下载见:https://www.cnblogs.c ...

  6. 翻翻git之---一个丰富的通知工具类 NotifyUtil

    转载请注明出处王亟亟的大牛之路 P1(废话板块.今天还加了个小广告) 昨天出去浪,到家把麦麦当当放出来玩一会就整到了12点多..早上睡过头了. .简直心酸. ... 近期手头上有一些职位能够操作,然后 ...

  7. Oracle 查询一个表的所有字段

    select * from user_tab_columns where table_name = 'T_B_CLIENT_MSG'

  8. eclipse svn插件 删除原账号信息重新登录

    1.通过删除SVN客户端的账号配置文件    1)查看你的Eclipse中使用的是什么SVN Interface(中文:svn接口)windows > preference > Team ...

  9. Session对象失效的客户端解决方法

    ASP(Active Server Pages)技术的Session对象用于存储用户在对话期间的私有信息.当前用户的Session对象中定义的变量和对象能在页面之间共享,但是不能为应用中其他用户所访问 ...

  10. 显存不够----ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[4096]

    ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[4096] 类似问题 h ...