Python之美[从菜鸟到高手]--threading daemon线程原理解读

本文探讨了Python中threading模块的daemon线程设置,解释了setDaemon(True)和setDaemon(False)对主线程结束的影响。通过分析,指出setDaemon(False)会导致主线程等待该线程结束,相当于调用了join方法。文章提醒程序员应避免使用无退出条件的while True循环,并指出良好的编程实践在Python世界中的重要性。
摘要由CSDN通过智能技术生成

事情的起因是我在看下面一段代码遇到的疑惑,明明是while True,为什么代码没有死循环??

class D(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        while  True:
            url = self.queue.get()
            self.download_file(url)
            self.queue.task_done()

    def download_file(self, url):
        h = urllib2.urlopen(url)
        f = os.path.basename(url)+'.html'
        with open(f,'wb') as f:
            while  True:
                c = h.read(1024)
                if not c:
                    break
                f.write(c)

if __name__ == "__main__":
    urls= ['http://www.baidu.com','http://www.sina.com']
    queue = Queue.Queue()
    for i in range(5):
        t = D(queue)
        t.setDaemon(True)
        t.start()

    for u in urls:
        queue.put(u)

    queue.join()

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值