Reputation: 161
I am making a simple project to learn about threading and this is my code:
import time
import threading
x = 0
def printfunction():
while x == 0:
print("process running")
def timer(delay):
while True:
time.sleep(delay)
break
x = 1
return x
t1 = threading.Thread(target = timer,args=[3])
t2 = threading.Thread(target = printfunction)
t1.start()
t2.start()
t1.join()
t2.join()
It is supposed to just print out process running
in the console for three seconds but it never stops printing. The console shows me no errors and I have tried shortening the time to see if I wasn't waiting long enough but it still doesn't work. Then I tried to delete the t1.join()
and t2.join()
but I still have no luck and the program continues running.
What am I doing wrong?
Upvotes: 1
Views: 146
Reputation: 70582
Add
global x
to the top of timer()
. As is, because timer()
assigns to x
, x
is considered to be local to timer()
, and its x = 1
has no effect on the module-level variable also named x
. The global x
remains 0 forever, so the while x == 0:
in printfunction()
always succeeds. It really has nothing to do with threading :-)
Upvotes: 1