简体   繁体   English

线程在 Python 3.6 中没有输出

[英]Threading Gives No Output in Python 3.6

Here's my code:这是我的代码:

import _thread
import time
def print_time(name, delay):
    count=1
    while count<=5:
        time.delay(delay)
        print ("Thread %s Time is %s"%(count, time.ctime(time.time())))
        count = count+1

_thread.start_new_thread(print_time,("T-1",2))
_thread.start_new_thread(print_time,("T-2",4))

The output should be various lines telling the current time.输出应该是告诉当前时间的不同行。 But after running the program I got no output and no error.但是在运行程序后,我没有输出也没有错误。 Why is this happening?为什么会这样? I use Python 3.6.我使用 Python 3.6。

Probably the first question is why you're using _thread .第一个问题可能是你为什么使用_thread I am guessing your issue is that your main thread finishes before print_time manages to produce any output, and on this particular system, that exits the whole program.我猜你的问题是你的主线程在print_time设法产生任何输出之前完成,并且在这个特定的系统上,退出整个程序。

From the section Caveats in the _thread documentation :_thread 文档中的警告部分:

When the main thread exits, it is system defined whether the other threads survive.当主线程退出时,其他线程是否存活由系统定义。 On most systems, they are killed without executing tryfinally clauses or executing object destructors.在大多数系统上,它们会在不执行try ... finally子句或执行对象析构函数的情况下被杀死。

When using threading instead, you get to choose whether to await threads with the daemon argument.当改用threading ,您可以选择是否使用daemon参数等待线程。

上面的答案总是更好的选择,但如果你仍然坚持使用_thread模块,只需在代码末尾添加time.sleep(1)延迟主线程

Use threading :使用threading

import threading
import time

def print_time(name, delay):
    count=1
    while count<=5:
        time.sleep(delay)
        print ("Thread %s Time is %s"%(count, time.ctime(time.time())))
        count = count+1

t1 = threading.Thread(target=print_time, args=("T-1",2))
t2 = threading.Thread(target=print_time, args=("T-2",4))

t1.start()
t2.start()

The threading module provides an easier to use and higher-level threading API built on top of this [ _thread ] module. threading 模块提供了一个更易于使用和更高级别的线程 API,它构建在这个 [ _thread ] 模块_thread

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

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