源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python守护线程用法实例

  • 时间:2021-08-23 22:24 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python守护线程用法实例
本文实例讲述了Python守护线程用法。分享给大家供大家参考,具体如下: 如果你设置一个线程为守护线程,就表示你在说这个线程是不重要的,在进程退出的时候,不用等待这个线程退出。如果你的主线程在退出的时候,不用等待那些子线程完成,那就设置这些线程的daemon属性。即在线程开始(thread.start())之前,调用setDeamon()函数,设定线程的daemon标志。(thread.setDaemon(True))就表示这个线程“不重要”。 如果你想等待子线程完成再退出,那就什么都不用做,或者显示地调用thread.setDaemon(False),设置daemon的值为false。新的子线程会继承父线程的daemon标志。整个Python会在所有的非守护线程退出后才会结束,即进程中没有非守护线程存在的时候才结束。 看下面的例子:
import time
import threading
def fun():
  print "start fun"
  time.sleep(2)
  print "end fun"
print "main thread"
t1 = threading.Thread(target=fun,args=())
#t1.setDaemon(True)
t1.start()
time.sleep(1)
print "main thread end"

结果:
main thread
start fun
main thread end
end fun

[b]结论:[/b]程序在等待子线程结束,才退出了。 [b]设置:[/b]setDaemon 为True
import time
import threading
def fun():
  print "start fun"
  time.sleep(2)
  print "end fun"
print "main thread"
t1 = threading.Thread(target=fun,args=())
t1.setDaemon(True)
t1.start()
time.sleep(1)
print "main thread end"

结果:
main thread
start fun
main thread end

[b]结论:[/b]程序在主线程结束后,直接退出了。 导致子线程没有运行完。 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/878.htm]Python进程与线程操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部