程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

10、 Python learning notes - process - start and join of process

編輯:Python
"""
1、 Process start Method execution process .
2、join Method blocks the main process , You need to wait for the corresponding child process to finish before continuing to execute the main process .
3、 Must be used in multiple processes join Method , Avoid zombie processes
"""
from multiprocessing import Process
import time
"""
1、 Defined function Foo1, The printing cycle is the first process .
2、 We are in function Foo1 Add different sleep Time to prove that it is multi process concurrent execution ( If yes, the parallel lines will be printed in the order of execution completion ,
If it is serial, it will follow 123 Sequential printing )
3、 Create an empty list p_list, Put three child processes into the list , Used to perform join
4、 establish 3 Subprocess execution Foo The function passes the number of cycles i
5、 Execute the subprocess (start)
6、 Execution blocking (join)
"""
def foo1(n):
m_list = [3, 2, 1]
time.sleep(m_list[n-1])
print(' This is the first {} A process '.format(n))
if __name__ == '__main__':
p_list = []
for i in range(1, 4):
p = Process(target=foo1, args=(i,))
p.start()
p_list.append(p)
for j in p_list:
j.join()
""" doubt : Why do you execute through a loop first 3 Subprocess , Then block through the circulation
1、 because join Will block the main process , If a child process is executed, it will block , This will cause the three processes to execute serially instead of concurrently .
2、 See the following example , We will start and join In a loop , In this way, a process will be executed first start and join, Then execute the next process in the loop .
3、 You can see their output , It's always 1,2,3. Description is serial .
"""
def foo2(n):
m_list = [3, 2, 1]
time.sleep(m_list[n-1])
print(' This is the first {} A process '.format(n))
if __name__ == '__main__':
for i in range(1, 4):
p = Process(target=foo2, args=(i,))
p.start()
p.join()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved