码迷,mamicode.com
首页 > 编程语言 > 详细

python 多进程

时间:2016-07-21 00:47:19      阅读:267      评论:0      收藏:0      [点我收藏+]

标签:

python 多进程

一、创建多进程的基本法方法

创建进程的类:Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。name为别名。group实质上不使用。

 

1、使用现成的Process类创建多线程

import multiprocessing
import time

def worker(interval):
    n = 5
    while n > 0:
        print("The time is {0}".format(time.ctime()))
        time.sleep(interval)
        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()

 

输出结果:
p.pid: 8736
p.name: Process-1
p.is_alive: True
The time is Tue Apr 21 20:55:12 2015
The time is Tue Apr 21 20:55:15 2015
The time is Tue Apr 21 20:55:18 2015
The time is Tue Apr 21 20:55:21 2015
The time is Tue Apr 21 20:55:24 2015

 

二、使用自定义的类创建多线程

import multiprocessing
import time

class MyProcess(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 = MyProcess(3)
    p.start()      
输出结果:
the time is Wed Jul 20 22:44:16 2016
the time is Wed Jul 20 22:44:19 2016
the time is Wed Jul 20 22:44:22 2016
the time is Wed Jul 20 22:44:25 2016
the time is Wed Jul 20 22:44:28 2016

 

说明:自定义多线程类需要重写run方法,执行自定义类的实例时会自动调用run方法。

 

3、守护进程

1)守护进程即守护主进程的进程,与主进程同生共死。

2)主进程退出时,守护进程也跟着退出。

3)默认情况下,创建的紫禁城程非守护进程,既主进程如果执行完毕的,而子进程没有执行完毕,主进程会等待子进程执行完毕后再退出。

4)设置守护进程的方法是 setDaemon = True。

 

def worker(interval):
    print("work start:{0}".format(time.ctime()));
    time.sleep(interval)
    print("work end:{0}".format(time.ctime()));

if __name__ == "__main__":
    p = multiprocessing.Process(target = worker, args = (3,))
    p.daemon = True
    p.start()
    print("end!")
输出结果:

end!

 

输出结果只有一个end!,子进程随着主进程的消亡而消亡,因为设置了守护进程。

python 多进程

标签:

原文地址:http://www.cnblogs.com/9527chu/p/5690020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!