[英]Python Creation of a semaphore or a check after finishing the execution of a list of threads
我正在運行一個需要運行許多外部命令的腳本。 我有幾個命令塊需要一起並行運行。
所以,我需要控制這個線程池已經完成以啟動下一個線程。
要運行的命令:
import pathlib
def thread_command(path_files, command):
_path_files= pathlib.Path(path_files)
if pathlib.Path(path_files).exists():
for file in _path_files.glob('**/*.ext'):
ext_file = Ext(file, path_files, tmp_rules)
if threads == None:
threads.insert(0, threading.Thread(target=command))
else:
threads.append(threading.Thread(target=command))
return threads
#Threads running
command1 = ext_file.command1
command2= ext_file.command2
threads1 = thread_command(pathToFiles, command1)
for thread in threads:
thread.daemon = True
thread.start()
do_other_things()
threads2 = thread_command(pathToFiles, command2)
for thread in threads2:
thread.daemon = True
thread.start()
我需要找到一種方法或過程來控制第一個線程列表何時完成以繼續執行程序。 總之,我想運行整個列表線程,並等待所有線程在那里運行完成,然后啟動第二個線程池。
提前感謝您的幫助。
不要使用“守護進程”線程,而是等待它們加入主線程,例如:
commands = [ext_file.command1, ext_file.command2] # etc.
for command in commands: # loop through commands in succession
# get the thread list and start it immediately
threads_list = [t for t in thread_command(pathToFiles, command) if t.start() is None]
for t in threads_list: # loop through all started threads and...
t.join() # ... wait for them to join back
但是您的thread_command()
函數本身沒有意義 - 對於初學者來說,當您嘗試插入/附加threads
列表時,您會收到錯誤消息,因為它未定義(至少不在函數上下文中)。 其次,為什么要為每個命令一遍又一遍地檢查文件列表,除非您希望文件列表發生變化?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.