python - 为什么python 2.5中threading.Thread通过阻塞执行来同步操作?

标签 python multithreading python-2.5

我仅限于python2.5,我认为threading.Thread是异步的。我运行: python t.py 并且脚本直到 3 秒过去才返回到 shell,这意味着它被阻塞。为什么会阻塞?

我的代码:

#!/usr/bin/python
import threading,time

def doit():
  time.sleep(3)
  print "DONE"

thr = threading.Thread(target=doit, args=(), kwargs={})
thr.start() # will run "foo"

最佳答案

默认情况下,Python 中的线程是非守护线程。 Python 应用程序 will not exit直到所有非守护线程完成,因此在您的情况下,直到 doit 完成之前它不会退出。如果您希望脚本在到达主线程末尾时立即退出,则需要通过设置 daemon attribute 使该线程成为守护进程。在启动线程之前:

thr = threading.Thread(target=doit, args=(), kwargs={})
thr.daemon = True
thr.start()

关于python - 为什么python 2.5中threading.Thread通过阻塞执行来同步操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26979711/

相关文章:

python - 从文本中的单词索引获取字符索引

python - 从不等形状的一维数组构造二维 numpy 数组 | NumPy 的

c++ - 如何在写入其他 std::atomic 之后强制读取 std::atomic?

.net - 用于设置 CurrentCulture 的线程创建事件

python - pandas reshape 元组 - 无法重新索引重复轴

python - 在 Python 3 中使用生成器的类似方法

java - java有可传输对象(多线程概念)

python - python中的中文和日文字符支持

python - 可以在 python 2.5 中做有序字典(由于 GAE)?