zoukankan      html  css  js  c++  java
  • 多线程之Semaphore信号量及

    Semphore,是一种带计数的线程同步机制,当调用release时,增加计数,当acquire时,减少计数,当计数为0时,自动阻塞,等待release被调用。

    指定数量的线程同时运行

    # Semaphore 是用于控制进入数量的锁
    # 文件, 读、写, 写一般只是用于一个线程写,读可以允许有多个
    
    # 做爬虫
    import threading
    import time
    
    
    class HtmlSpider(threading.Thread):
        def __init__(self, url, sem):
            super().__init__()
            self.url = url
            self.sem = sem
    
        def run(self):
            time.sleep(2)
            print("got html text success\n")
            self.sem.release()
    
    
    class UrlProducer(threading.Thread):
        def __init__(self, sem):
            super().__init__()
            self.sem = sem
    
        def run(self):
            for i in range(20):
                self.sem.acquire()
                html_thread = HtmlSpider("https://baidu.com/{}".format(i), self.sem)
                html_thread.start()
    
    
    if __name__ == "__main__":
        sem = threading.Semaphore(3)
        url_producer = UrlProducer(sem)
        url_producer.start()
    

    BoundedSemaphore在调用release()的时候,会校验一下当前信号量的值,是否会大于初始值(只定义了20个信号量,释放了20次后,还要调用release)的场景,会抛出异常,而 Semaphore在这种场景下,release()的结果只是None,没有返回信号量对象,并不会抛出异常。

  • 相关阅读:
    python3 flask 文件下载服务器
    jquery cdn加速
    cherry 与sqlite
    cherry 与react.js
    cherrypy json 解析
    cherrypy cookies
    cherrypy 打印日志
    cherrypy pytest 覆盖,测试代码
    cherrypy ajax 请求
    cherrypy 访问css文件
  • 原文地址:https://www.cnblogs.com/yoyo1216/p/15740580.html
Copyright © 2011-2022 走看看