您还可以使用计时器来完成以下代码中的工作。
我自愿将 15 秒用于线程 2,以便人们可以看到它在时间过去后有效地结束在最后一个位置。
此代码示例有两个主要功能。
第一个 your_process_here() 就像它的名字所说的那样正在等待你自己的代码
第二个是一个管理器,它组织线程切片以避免系统过载。
参数
max_process:脚本正在执行的进程总数
simultp:最大同时进程数
timegl:时间准则,它定义了自父级启动以来每个线程的等待时间。所以等待时间至少是指南中定义的时间(指父母的开始时间)。
换句话说,由于它的指导时间已经过去,考虑到允许的最大并发线程数,线程会尽快启动。
在这个例子中
最大进程 = 6
simultp = 3
timegl = [1, 15, 1, 0.22, 6, 0.5](只是为了解释,因为更合乎逻辑的是那里有一个增加系列)
shell 中的结果
同时启动的进程:3
进程 n°2 处于活动状态,将在治疗功能开始前再等待 14.99 秒
进程 n°1 处于活动状态,将在治疗功能开始前再等待 0.98 秒
进程 n°3 处于活动状态,将在治疗功能开始前再等待 0.98 秒
---- 进程 n°1 结束 ----
---- 进程 n°3 结束 ----
同时启动的进程:3
进程 n°5 处于活动状态,将在治疗功能开始前再等待 2.88 秒
进程 n°4 处于活动状态,现在将开始
---- 进程 n°4 结束 ----
---- 进程 n°5 结束 ----
同时启动的进程:2
进程 n°6 处于活动状态,现在将开始
---- 进程 n°6 结束 ----
---- 进程 n°2 结束 ----
代码
import multiprocessing as mp
from threading import Timer
import time
def your_process_here(starttime, pnum, timegl):
# Delay since the parent thread starts
delay_since_pstart = time.time() - starttime
# Time to sleep in order to follow the most possible the time guideline
diff = timegl[pnum-1]- delay_since_pstart
if diff > 0: # if time ellapsed since Parent starts < guideline time
print('process n°{0} is active and will wait {1} seconds more before treatment function starts'\
.format(pnum, round(diff, 2)))
time.sleep(diff) # wait for X more seconds
else:
print('process n°{0} is active and will start now'.format(pnum))
########################################################
## PUT THE CODE AFTER SLEEP() TO START CODE WITH A DELAY
## if pnum == 1:
## function1()
## elif pnum == 2:
## function2()
## ...
print('---- process n°{0} ended ----'.format(pnum))
def process_manager(max_process, simultp, timegl, starttime=0, pnum=1, launchp=[]):
# While your number of simultaneous current processes is less than simultp and
# the historical number of processes is less than max_process
while len(mp.active_children()) < simultp and len(launchp) < max_process:
# Incrementation of the process number
pnum = len(launchp) + 1
# Start a new process
mp.Process(target=your_process_here, args=(starttime, pnum, timegl)).start()
# Historical of all launched unique processes
launchp = list(set(launchp + mp.active_children()))
# ...
####### THESE 2 FOLLOWING LINES ARE TO DELETE IN OPERATIONAL CODE ############
print('simultaneously launched processes : ', len(mp.active_children()))
time.sleep(3) # optionnal : This a break of 3 seconds before the next slice of process to be treated
##############################################################################
if pnum < max_process:
delay_repeat = 0.1 # 100 ms
# If all the processes have not been launched renew the operation
Timer(delay_repeat, process_manager, (max_process, simultp, timegl, starttime, pnum, launchp)).start()
if __name__ == '__main__':
max_process = 6 # maximum of processes
simultp = 3 # maximum of simultaneous processes to save resources
timegl = [1, 15, 1, 0.22, 6, 0.5] # Time guideline
starttime = time.time()
process_manager(max_process, simultp, timegl, starttime)