无法按照预期退出

来源:11-3 线程间通信 - 共享变量和 Queue

慕无忌2744351

2018-08-06

def get_detail_html(queue):
   # 爬取文章详情页
   while True:
       for i in range(5):
           url = queue.get()
           print("get detail html started") #该行缩近一个单元则能正常退出
       time.sleep(2)
       for i in range(5):
           queue.task_done()
       print("get detail html end")
def get_detail_url(queue):
   # 爬取文章列表页
   for i in range(20):
       queue.put("http://projectsedu.com/{id}".format(id=i))
# 1. 线程通信方式- 共享变量
if __name__ == "__main__":
   detail_url_queue = Queue(maxsize=1000)
   thread_detail_url = threading.Thread(target=get_detail_url, args=(detail_url_queue,))
   for i in range(10):
       html_thread = threading.Thread(target=get_detail_html, args=(detail_url_queue,))
       html_thread.setDaemon(True)
       html_thread.start()
   start_time = time.time()
   thread_detail_url.start()
   detail_url_queue.join()

   # 当主线程退出的时候, 子线程kill掉
   print("last time: {}".format(time.time() - start_time))

写回答

1回答

bobby

2018-08-08

如果启用t.setDaemon(True),这段代码的运行流程是:当主线程打印完最后一句话后,不管 son thread 是否运行完,程序立即结束,你现在的情况是什么呢?

0
2
bobby
回复
慕无忌2744351
http://www.vuln.cn/8610 你可以看看这个
2018-08-10
共2条回复

Python3高级核心技术97讲,高级进阶的必学课程

socket编程/多线程/多进程/线程池/asyncio并发编程/协程和异步IO

2121 学习 · 551 问题

查看课程