VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Python基础教程 >
  • python基础教程之Python—创建进程的三种方式(2)

方式二:multiprocessing.Process()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# --coding:utf8--
from multiprocessing import Process
import os,time,random
 
def test(num, msg):
    print "---子进程的pid=%d, ppid=%d, num=%d, msg=%s" % (os.getpid(), os.getppid(), num, msg)
    for in range(random.randint(15)):
        print("----%d---"%i)
        time.sleep(1)
 
# p = Process(target=test, args=(), kwargs={})   # 当函数没有参数时候,可以这样写
= Process(target=test, args=(100,), kwargs={"msg":"hello"})
p.start() # 让这个进程开始执行test函数里的代码
p.join()  # 堵塞,可以加参数p.join(1)。等到p这个对象标记的进程结束之后,才会继续向下走
 
print "---父进程的pid=%d" % os.getpid()

方式三:继承multiprocessing.Process类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from multiprocessing import Process
import os, time
 
# 自定义的进程类
class MyProcess(Process):
    def __init__(self, value):
        self.value = value
        Process.__init__(self)
        # super(MyProcess,self).__init__()
        
    # 在自定义的进程类中重写父类(Process)的run()方法
    def run(self):
        print "---子进程:%s开始执行,父进程pid:%s"%(os.getpid(),os.getppid())
        while True:
            print("---传的参数值为:%d---" % self.value)
            time.sleep(1)
 
if __name__ == '__main__':
    = MyProcess(3)
    p.start()
    p.join(6)   # 阻塞等到子进程执行结束,超时时间为6秒。不加参数,会一直阻塞等待下去。
    while True:
        print "---main---"
        time.sleep(1)
相关教程