1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.