I want to pause a thread in python when another function is called. In the code below, f2
is of higher priority, and f1
should wait until it completes. After reading this post I tried this:
import threading
import time
class c:
def f1():
for j in range(7):
print ("f1")
time.sleep(0.5)
def f2():
with lock:
for i in range(3):
print(i)
time.sleep(1)
lock = threading.Lock()
threading.Thread(target=c.f1).start()
f2()
but the result is this
f1
0
f1
1
f1
f1
2
f1
f1
f1
while the expected output should be this
f1
0
1
2
f1
f1
f1
f1
f1
f1
What is going wrong?
If I add with lock
inside f1
before or after the for
I get this result
f1
f1
f1
f1
f1
f1
f1
0
1
2
which is equally undesirable.
Also please note that the code structure is important. If you offer a solution please keep the same structure, meaning function f1
inside class c
and the rest in the global scope. Only one thread is created in total.
Thank you