[英]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.