美文网首页
Python多进程用到的方法

Python多进程用到的方法

作者: 林清猫耳 | 来源:发表于2018-04-04 22:13 被阅读13次

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)

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  #以最长时间的为主

terminate() :

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

相关文章

网友评论

      本文标题:Python多进程用到的方法

      本文链接:https://www.haomeiwen.com/subject/chilhftx.html