如何在 Python 中修复线程的这个基本示例

How to fix this basic example of threading in Python

我正在尝试自学如何在 Python 中使用线程。我想出了一个基本问题,试图中断一个函数,该函数将在 10 秒后永远继续打印数字的平方。我以这个网站为例:http://zulko.github.io/blog/2013/09/19/a-basic-example-of-threads-synchronization-in-python/。我现在拥有的代码无法按预期工作,我想知道你们中的任何人是否可以帮助我修复它,以便我可以更好地理解线程。提前致谢!

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