Python在完成线程列表的执行后创建信号量或检查

2024-04-23 17:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我运行的脚本需要运行许多外部命令。我有几个命令块需要一起并行运行。你知道吗

因此,我需要控制这个线程池是否已完成,以启动下一个线程池。你知道吗

要运行的命令:

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()

我需要找到一种方法或一个过程来控制线程的第一个列表何时完成,以继续执行程序。 总之,我想运行整个列表线程,并等待所有在那里运行的线程完成,然后启动第二个线程池。你知道吗

提前谢谢你的帮助。你知道吗


Tags: pathin命令forfiles线程threadext
1条回答
网友
1楼 · 发布于 2024-04-23 17:04:02

不要使用“daemon”线程,而是等待它们连接回主线程,例如:

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列表时,你会得到一个错误,因为它没有被定义(至少不在函数上下文中)。第二,为什么要一遍又一遍地检查每个命令的文件列表,除非您希望文件列表发生更改?你知道吗

相关问题 更多 >