Mark~ Mark~ Mark~~~~~~~~~~~~~~~~~~~~~~
msg: hello 0
msg: hello 1
msg: hello 2
end
msg: hello 3
end
msg: hello 4
end
msg: hello 5
end
msg: hello 6
end
msg: hello 7
end
msg: hello 8
end
msg: hello 9
end
end
end
Sub-process(es) done.
执行说明:创建一个进程池pool,并设定进程的数量为3,range(4)会相继产生四个对象[0, 1, 2, 3,4,5,6,7,8,9],十个对象被提交到pool中,因pool指定进程数为3,所以0、1、2会直接送到进程中执行,当其中一个执行完事后才空出一个进程处理对象3,所以会出现输出“msg: hello 3”出现在"end"后。因为为非阻塞,主函数会自己执行自个的,不搭理进程的执行,所以运行完for循环后直接输出“mMsg: hark~ Mark~ Mark~~~~~~~~~~~~~~~~~~~~~~”,主程序在pool.join()处等待各个进程的结束。
1 import multiprocessing
2 import time
3
4 def func(msg):
5 print ("msg:", msg)
6 time.sleep(3)
7 print ("end")
8
9 if __name__ == "__main__":
10 pool = multiprocessing.Pool(processes = 3) # 池中最大进程数为3
11 for i in range(10):
12 msg = "hello %d" %(i)
13 pool.apply(func, (msg, )) #维持执行的进程总数为processes,当一个进程执行完毕后会添加新的进程进去
14
15 print ("Mark~ Mark~ Mark~~~~~~~~~~~~~~~~~~~~~~")
16 pool.close()
17 pool.join() #调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
18 print ("Sub-process(es) done.")
19
20 # 运行结果
21 '''
22 msg: hello 0
23 end
24 msg: hello 1
25 end
26 msg: hello 2
27 end
28 msg: hello 3
29 end
30 msg: hello 4
31 end
32 msg: hello 5
33 end
34 msg: hello 6
35 end
36 msg: hello 7
37 end
38 msg: hello 8
39 end
40 msg: hello 9
41 end
42 Mark~ Mark~ Mark~~~~~~~~~~~~~~~~~~~~~~
43 Sub-process(es) done.
44 '''
1 import multiprocessing
2 import os, time, random
3
4
5 def Lee():
6 print("\nRun task Lee-%s" % (os.getpid())) # os.getpid()获取当前的进程的ID
7 start = time.time()
8 time.sleep(random.random() * 10) # random.random()随机生成0-1之间的小数
9 end = time.time()
10 print( 'Task Lee, runs %0.2f seconds.' % (end - start))
11
12
13 def Marlon():
14 print("\nRun task Marlon-%s" % (os.getpid()))
15 start = time.time()
16 time.sleep(random.random() * 40)
17 end = time.time()
18 print('Task Marlon runs %0.2f seconds.' % (end - start))
19
20
21 def Allen():
22 print("\nRun task Allen-%s" % (os.getpid()))
23 start = time.time()
24 time.sleep(random.random() * 30)
25 end = time.time()
26 print('Task Allen runs %0.2f seconds.' % (end - start))
27
28
29 def Frank():
30 print( "\nRun task Frank-%s" % (os.getpid()))
31 start = time.time()
32 time.sleep(random.random() * 20)
33 end = time.time()
34 print( 'Task Frank runs %0.2f seconds.' % (end - start))
35
36
37 if __name__ == '__main__':
38 function_list = [Lee, Marlon, Allen, Frank]
39 print("parent process %s" % (os.getpid()))
40
41 pool = multiprocessing.Pool(4)
42 for func in function_list:
43 pool.apply_async(func) # Pool执行函数,apply执行函数,当有一个进程执行完毕后,会添加一个新的进程到pool中
44
45 print('Waiting for all subprocesses done...')
46 pool.close()
47 pool.join() # 调用join之前,一定要先调用close() 函数,否则会出错, close()执行后不会有新的进程加入到pool,join函数等待素有子进程结束
48 print( 'All subprocesses done.')
49
50 # 运行结果
51 '''
52 parent process 3256
53 Waiting for all subprocesses done...
54
55 Run task Lee-2196
56
57 Run task Marlon-4580
58
59 R