Tullio_IRL Tullio_IRL - 1 month ago 6
Python Question

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

I'm new enough to python programming and starting to dabble with concurrency for the first time, so please forgive any terms.

My programme starts two threads with each call a function "lightshow()" but rather than the programme stalling it's execution until both threads have completed it moves on to the next line in the code.

Is it possible to "pause" the progamme until both threads have completed?

Below is my code snippet:

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


Basically the programme switches two relays simultaneously to switch on lights with different on/off patterns.

If there's a better way other than threading please let me know.

Many thanks,

Paul

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

but since its just a hardcoded timeout why not just

time.sleep(61)