【问题标题】:How to fix this basic example of threading in Python如何在 Python 中修复这个基本的线程示例
【发布时间】:2025-12-27 16:55:07
【问题描述】:

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

【问题讨论】:

  • threading.Thread(target=square, args = (go_off)):您正在传递一个函数,其中需要一个数字来计算平方...
  • @Jean-FrançoisFabre 你能解释一下我应该怎么做吗?如果我用 threading.Thread(target=square(6), args = (go_off)) 替换它,程序会继续无限期地打印出 36 而不会停止。
  • threading.Thread(target=square(6)) 调用线程外的例程。那是经典。看我的回答。
  • 对于所有可能回答的人,为了清楚起见,我正在尝试向程序发出信号,停止打印数字的平方。
  • Threads and Synchronization ?废话... cpu_clock 的确定值如何?检查我的问题...

标签: python multithreading python-2.7 python-multithreading


【解决方案1】:
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()

【讨论】:

  • 另一种选择是将 Event(go_off) 作为参数传递给函数
  • 非常感谢!你太棒了!