【问题标题】:Why doesn't my timer thread run in python?为什么我的计时器线程不在 python 中运行?
【发布时间】:2020-07-23 16:01:34
【问题描述】:

我正在做一个简单的项目来学习线程,这是我的代码:

import time
import threading

x = 0

def printfunction():
    while x == 0:
        print("process running")


def timer(delay):
    while True:
        time.sleep(delay)
        break
    x = 1
    return x

t1 = threading.Thread(target = timer,args=[3])
t2 = threading.Thread(target = printfunction)

t1.start()
t2.start()
t1.join()
t2.join()

它应该只是在控制台中打印出process running 三秒钟,但它永远不会停止打印。控制台没有显示任何错误,我尝试缩短时间,看看我是否等待的时间不够长,但它仍然不起作用。然后我尝试删除t1.join()t2.join(),但我仍然没有运气,程序继续运行。

我做错了什么?

【问题讨论】:

    标签: python multithreading time python-multiprocessing python-multithreading


    【解决方案1】:

    添加

    global x
    

    timer() 的顶部。因为timer() 分配给x,所以x 被认为是timer() 的局部变量,并且它的x = 1 对也名为x 的模块级变量没有影响。全局x 永远保持为0,所以printfunction() 中的while x == 0: 总是成功。它真的与线程无关:-)

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多