我试图教自己如何在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()

关于python - 如何修复Python中这个基本的线程示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42973343/

10-11 16:17