I have a problem to start first thread, wait until end of first thread, start second thread, wait until finish of second thread and again go to first thread and do that in infinite loop.
The result I'm getting it's not working as it should because it's printing threads without time delay...
Here's my code:
import threading
import time
def Thread1():
while True:
print("THREAD 1")
time.sleep(3)
def Thread2():
while True:
print("THREAD 2")
time.sleep(6)
Thread1 = threading.Thread(target = Thread1)
Thread2 = threading.Thread(target = Thread2)
Thread1.start()
Thread2.start()
Thread2.join()
I want the result to be:
THREAD1
(3s pause)
THREAD2
(6s pause)
THREAD1
(3s pause)
THREAD2
(6s pause)
... (infinite loop)
CodePudding user response:
You can play ping-pong with Event
s from the threading library:
import threading
import time
ping = threading.Event()
pong = threading.Event()
def thread1():
while True:
ping.wait()
print("THREAD 1")
time.sleep(3)
ping.clear()
pong.set()
def thread2():
while True:
pong.wait()
print("THREAD 2")
time.sleep(6)
pong.clear()
ping.set()
t1 = threading.Thread(target = thread1)
t2 = threading.Thread(target = thread2)
t1.start()
t2.start()
ping.set()
t2.join()
This creates two events ping
and pong
. When ping
is triggered the first thread is allowed to run. When it finishes, is clears the events and triggers pong
which allows the second thread to run, etc.
Not sure if this is the best way but it seems to work.