Python 创建进程

1.例子

 1 #__author: Lobin
 2 #__date:   2018/1/24
 3 from multiprocessing import Process
 4 import time
 5 def f(name):
 6     time.sleep(1)
 7     print('hello', name,time.ctime())
 8 
 9 if __name__ == '__main__':
10     p_list=[]
11     for i in range(3):
12         p = Process(target=f, args=('alvin',))
13         p_list.append(p)
14         p.start()
15     for i in p_list:
16         p.join()
17     print('end')

结果

1 #hello alvin Wed Jan 24 23:42:36 2018
2 #hello alvin Wed Jan 24 23:42:36 2018
3 #hello alvin Wed Jan 24 23:42:36 2018
4 #end

2.例子

 1 from multiprocessing import Process
 2 import time
 3 class MyProcess(Process):
 4     def __init__(self):
 5         super(MyProcess, self).__init__()
 6         #self.name = name
 7     def run(self):
 8         time.sleep(1)
 9         print ('hello', self.name,time.ctime())
10 if __name__ == '__main__':
11     p_list=[]
12     for i in range(3):
13         p = MyProcess()
14         p.start()
15         p_list.append(p)
16     for p in p_list:
17         p.join()
18     print('end')

结果

1 #hello MyProcess-1 Wed Jan 24 23:44:30 2018
2 #hello MyProcess-2 Wed Jan 24 23:44:30 2018
3 #hello MyProcess-3 Wed Jan 24 23:44:30 2018
4 #end

3.例子

 1 from multiprocessing import Process
 2 import os
 3 import time
 4 def info(title):
 5     print(title)
 6     print('module name:', __name__)
 7     print('parent process:', os.getppid())
 8     print('process id:', os.getpid())
 9 
10 
11 def f(name):
12     info('\033[31;1mfunction f\033[0m')
13     print('hello', name)
14 
15 if __name__ == '__main__':
16     info('\033[32;1mmain process line\033[0m')
17     time.sleep(3)
18     p = Process(target=info, args=('bob',))
19     p.start()
20     p.join()

结果

 

posted on 2018-01-25 00:30  可爱的春哥  阅读(90)  评论(0)    收藏  举报

导航