Laura Holewa Laura Holewa -4 years ago 130
Python Question

How to fix this basic example of threading in Python

I am trying to teach myself how to use threading in Python. I have come up with the basic problem of trying to interrupt a function that would continue printing the square of a number forever after only 10 seconds. I used this website as an example: http://zulko.github.io/blog/2013/09/19/a-basic-example-of-threads-synchronization-in-python/. The code that I have now does not work as intended and I'm wondering if any of you could help me fix it so I can understand threading better. Thank you in advance!

import threading
import time

def square(x):
while 1==1:
time.sleep(5)
y=x*x
print y

def alarm():
time.sleep(10)
go_off.set()


def go():
go_off= threading.Event()
squaring_thread = threading.Thread(target=square, args = (go_off))
squaring_thread.start()
square(5)
go()

Answer Source
import threading
import time
#Global scope to be shared across threads
go_off = threading.Event()

def square(x):
    while not go_off.isSet():
        time.sleep(1)
        print x*x

def alarm():
    time.sleep(10)
    go_off.set()


def go():
    squaring_thread = threading.Thread(target=square,args = (6,))
    alarm_thread = threading.Thread(target=alarm , args = ())
    alarm_thread.start()
    squaring_thread.start()
go()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download