Python:如何暂停函数的执行直到两个线程完成

Python: how to stall execution of function until two threads complete

我是 python 编程新手,第一次开始涉足并发,所以请原谅任何条款。

我的程序启动了两个线程,每个线程都调用了一个函数 "lightshow()",但程序并没有停止执行,直到两个线程都完成后才继续执行代码中的下一行。

是否可以"pause"程序直到两个线程都完成?

下面是我的代码片段:

import time
import threading
from threading import Thread

# Handshake pulse on GPIO2 of 4 50ms highs

def setup():
        for pulse in range(5):
                hs.on()
                sleep(0.05)
                hs.off()
                sleep(0.05)
        print('handshake comlete')

def lightshow(sequence, relay):
        t_end = time.time() + 60*1
        while time.time() < t_end:
                print('starting timer')
                # iterate over the dictionary's keys and values 
                for key, value in sequence.items():
                        relay.on()
                        sleep(key)
                        relay.off()
                        sleep(value)



setup() #send handshake to board to prime it.


t1 = threading.Thread(target = lightshow, args=(flickerRGB, relay1))
t2 = threading.Thread(target = lightshow, args=(flickerWhite, relay2))

t1.start()
t2.start()

#send handshake to Relay board to reset it
setup()

基本上,程序同时切换两个继电器以打开具有不同 on/off 模式的灯。

如果有比线程更好的方法,请告诉我。

非常感谢,

保罗

#send handshake to Relay board to reset it
t2.join() #block until thread exits
setup()

但既然它只是一个硬编码超时,为什么不直接

time.sleep(61)