Python进程


1.创建进程

  multiprocessing模块就是跨平台版本的多进程模块,提供了一个Process类来代表一个进程对象,

这个对象可以理解为是一个独立的进程,可以执行另外的事情。 示例:创建一个进程,执行两个死循环
 1 from multiprocessing import Process
 2 import time
 3 
 4 
 5 def run_proc():
 6     """子进程要执行的代码"""
 7     while True:
 8         print("----2----")
 9         time.sleep(1)
10 
11 
12 if __name__=='__main__':
13     p = Process(target=run_proc)
14     p.start()
15     while True:   
16         print("----1----")
17         time.sleep(1)

说明:

  创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动
方法说明:

  Process( target [, name [, args [, kwargs]]])   target:如果传递了函数的引用,可以任务这个子进程就执行这里的代码   args:给target指定的函数传递的参数,以元组的方式传递   kwargs:给target指定的函数传递命名参数   name:给进程设定一个名字,可以不设定   
Process创建的实例对象的常用方法:   start():启动子进程实例(创建子进程)   is_alive():判断进程子进程是否还在活着   join([timeout]):是否等待子进程执行结束,或等待多少秒   terminate():不管任务是否完成,立即终止子进程   
Process创建的实例对象的常用属性:   name:当前进程的别名,默认为Process
-N,N为从1开始递增的整数   pid:当前进程的pid(进程号)
 1 from multiprocessing import Process
 2 import os
 3 from time import sleep
 4 
 5 
 6 def run_proc(name, age, **kwargs):
 7     for i in range(10):
 8         print('子进程运行中,name= %s,age=%d ,pid=%d...' % (name, age, os.getpid()))
 9         print(kwargs)
10         sleep(0.2)
11 
12 if __name__=='__main__':
13     p = Process(target=run_proc, args=('test',18), kwargs={"m":20})
14     p.start()
15     sleep(1)  # 1秒中之后,立即结束子进程
16     p.terminate()
17     p.join()
18 
19 '''
20 子进程运行中,name= test,age=18 ,pid=27044...
21 {'m': 20}
22 子进程运行中,name= test,age=18 ,pid=27044...
23 {'m': 20}
24 子进程运行中,name= test,age=18 ,pid=27044...
25 {'m': 20}
26 子进程运行中,name= test,age=18 ,pid=27044...
27 {'m': 20}
28 子进程运行中,name= test,age=18 ,pid=27044...
29 {'m': 20}
30 '''

2.进程间不能共享全局变量

 1 from multiprocessing import Process
 2 import os
 3 
 4 nums = [11, 22]
 5 
 6 
 7 def work1():
 8     """子进程要执行的代码"""
 9     print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))
10     for i in range(3):
11         nums.append(i)
12         print("in process1 pid=%d ,nums=%s" % (os.getpid(), nums))
13 
14 
15 def work2():
16     """子进程要执行的代码"""
17     nums.pop()
18     print("in process2 pid=%d ,nums=%s" % (os.getpid(), nums))
19 
20 
21 if __name__ == '__main__':
22     p1 = Process(target=work1)
23     p1.start()
24     p1.join()
25 
26     p2 = Process(target=work2)
27     p2.start()
28 
29     print('in process0 pid={} ,nums={}'.format(os.getpid(), nums))
30 
31 '''
32 in process1 pid=13284 ,nums=[11, 22]
33 in process1 pid=13284 ,nums=[11, 22, 0]
34 in process1 pid=13284 ,nums=[11, 22, 0, 1]
35 in process1 pid=13284 ,nums=[11, 22, 0, 1, 2]
36 in process0 pid=27444 ,nums=[11, 22]
37 in process2 pid=28168 ,nums=[11]
38 '''