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

Python multitasking programming -- process waiting

編輯:Python

Process waiting purpose :

The main process will wait for all child processes to finish executing before exiting .

The goal is :

The main process exits and the child process is destroyed

resolvent :

1. Set the subprocess as the main daemon , The main process exits and the child process is destroyed directly

adopt sub_process.daemon = True Realization

import multiprocessing
import time
def task():
while True:
print("waiting...")
time.sleep(1)
# standard python How to write it , Directly executed modules , You need to add the code to determine whether it is the main module
if __name__ == '__main__':
# Create child process
sub_process = multiprocessing.Process(target=task)
# Set the subprocess as the main daemon , After that, the main process exits the child process and is destroyed directly
sub_process.daemon = True
sub_process.start()
# Main process delay 5 Second
time.sleep(5)
print("over")

Running results :

2. Before exiting the main process , Let the child process destroy first

sub_process.terminate()

import multiprocessing
import time
def task():
# for i in range(10):
while True:
print("waiting...")
time.sleep(1)
# standard python How to write it , Directly executed modules , You need to add the code to determine whether it is the main module
if __name__ == '__main__':
# Create child process
sub_process = multiprocessing.Process(target=task)
sub_process.start()
# Main process delay 10 Second
time.sleep(10)
# Before exiting the main process , Let the child process destroy first
sub_process.terminate()
print("over")

Running results :


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