[英]Threading Gives No Output in Python 3.6
这是我的代码:
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))
输出应该是告诉当前时间的不同行。 但是在运行程序后,我没有输出也没有错误。 为什么会这样? 我使用 Python 3.6。
第一个问题可能是你为什么使用_thread
。 我猜你的问题是你的主线程在print_time
设法产生任何输出之前完成,并且在这个特定的系统上,退出整个程序。
从_thread 文档中的警告部分:
当主线程退出时,其他线程是否存活由系统定义。 在大多数系统上,它们会在不执行
try
...finally
子句或执行对象析构函数的情况下被杀死。
当改用threading
,您可以选择是否使用daemon
参数等待线程。
上面的答案总是更好的选择,但如果你仍然坚持使用_thread
模块,只需在代码末尾添加time.sleep(1)
延迟主线程
使用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()
threading 模块提供了一个更易于使用和更高级别的线程 API,它构建在这个 [
_thread
] 模块_thread
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.