主线程和子线程都运行完了,怎么还是没有退出?下面是代码,会一直运行,这是为什么?

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

Yan雪杉

2018-06-24

from queue import Queue
import time
import threading


def get_detail_html(queue):
    #爬取文章详情页
    url = queue.get()
    # for url in detail_url_list:
    print("get detail html started")
    time.sleep(2)
    print("get detail html end")
    queue.task_done()


def get_detail_url(queue):
    # 爬取文章列表页
    print("get detail url started")
    # time.sleep(4)
    for i in range(5):
        queue.put("http://projectsedu.com/{id}".format(id=i))
    print("get detail url end")


#1. 线程通信方式- 共享变量

if  __name__ == "__main__":
    detail_url_queue = Queue(maxsize=1000)

    thread_detail_url = threading.Thread(target=get_detail_url, args=(detail_url_queue,))
    thread_detail_url.start()
    for i in range(6):
        html_thread = threading.Thread(target=get_detail_html, args=(detail_url_queue, ))
        html_thread.start()
    # # thread2 = GetDetailUrl("get_detail_url")
    start_time = time.time()

    # thread_detail_url1.start()
    #
    # thread1.join()
    # thread2.join()
    # detail_url_queue.task_done()
    detail_url_queue.join()

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


写回答

1回答

bobby

2018-06-26

url = queue.get() 该方法会一直阻塞 导致一直无法运行到task_done你需要用get_nowait方法

0
1
Yan雪杉
非常感谢!
2018-06-26
共1条回复

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

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

2121 学习 · 551 问题

查看课程