zoukankan      html  css  js  c++  java
  • 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))
  • 相关阅读:
    java List转换为字符串并加入分隔符的一些方法总结
    jackson 实体转json 为NULL或者为空不参加序列化
    马云告别演讲
    Linux chmod命令
    Linux执行shell脚本的方法
    2019第36周日
    2019第36周六
    eclipse中的maven插件
    SpringBoot要点之使用Actuator监控
    eclipse隐藏的列编辑
  • 原文地址:https://www.cnblogs.com/callyblog/p/11142098.html
Copyright © 2011-2022 走看看