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

时间:2017-03-23 10:25:52

标签: python multithreading python-2.7 python-multithreading

我正在尝试自学如何在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()

1 个答案:

答案 0 :(得分:2)

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