python 使用隊列實現線程同步


#通過queue的方式進行線程間同步,Queue在底層通過實現了dqueue(雙生隊列,在字節碼時實現了線程安全)實現了線程安全
from queue import Queue


import time
import threading


def get_detail_html(queue):
    #爬取文章詳情頁
    while True:
        url = queue.get()# 如果沒有數據會一直阻塞在這
        # for url in detail_url_list:
        print("get detail html started")
        time.sleep(2)
        print("get detail html end")


def get_detail_url(queue):
    # 爬取文章列表頁
    while True:
        print("get detail url started")
        time.sleep(4)
        for i in range(20):
            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,))
    for i in range(10):
        html_thread = threading.Thread(target=get_detail_html, args=(detail_url_queue,))
        html_thread.start()
    start_time = time.time()

    detail_url_queue.task_done() # 隊列任務完成,只有調用這個,線程才會退出
    detail_url_queue.join() # 阻塞主線程,調用了task_done,queue才會退出,不然一直會阻塞在queue這

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM