简体   繁体   English

为什么我的计时器线程不在 python 中运行?

[英]Why doesn't my timer thread run in python?

I am making a simple project to learn about threading and this is my code:我正在制作一个简单的项目来学习线程,这是我的代码:

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

It is supposed to just print out process running in the console for three seconds but it never stops printing.它应该只打印出在控制台process running ,但它永远不会停止打印。 The console shows me no errors and I have tried shortening the time to see if I wasn't waiting long enough but it still doesn't work.控制台没有显示任何错误,我尝试缩短时间,看看我是否等待的时间不够长,但它仍然不起作用。 Then I tried to delete the t1.join() and t2.join() but I still have no luck and the program continues running.然后我尝试删除t1.join()t2.join()但我仍然没有运气,程序继续运行。

What am I doing wrong?我究竟做错了什么?

Add添加

global x

to the top of timer() .timer()的顶部。 As is, because timer() assigns to x , x is considered to be local to timer() , and its x = 1 has no effect on the module-level variable also named x .因为timer()分配给x ,所以x被认为是timer()的局部变量,并且它的x = 1对也名为x的模块级变量没有影响。 The global x remains 0 forever, so the while x == 0: in printfunction() always succeeds.全局x永远保持为 0,因此printfunction()中的while x == 0:总是成功。 It really has nothing to do with threading:-)它真的与线程无关:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM