zoukankan      html  css  js  c++  java
  • python3 Semaphore

    同进程的一样
    Semaphore管理一个内置的计数器,
    每当调用acquire()时内置计数器-1;
    调用release() 时内置计数器+1;
    计数器不能小于0;当计数器为0时,acquire()将阻塞线程直到其他线程调用release()。
     
    实例:(同时只有5个线程可以获得semaphore,即可以限制最大连接数为5):
    from threading import Thread,Semaphore
    import threading
    import time
     
    def task():
        sm.acquire()
        print(f"{threading.current_thread().name} get sm")
        time.sleep(3)
        sm.release()
     
     
    if __name__ == '__main__':
        sm = Semaphore(5) # 同一时间只有5个线程可以执行。
        for i in range(20):
            t = Thread(target=task)
            t.start()
    outputs 
    macname@MacdeMacBook-Pro py % python3 cccccc.py
    Thread-1 get sm
    Thread-2 get sm
    Thread-4 get sm
    Thread-5 get sm
    Thread-3 get sm
    Thread-6 get sm
    Thread-7 get sm
    Thread-9 get sm
    Thread-10 get sm
    Thread-8 get sm
    Thread-11 get sm
    Thread-13 get sm
    Thread-12 get sm
    Thread-14 get sm
    Thread-15 get sm
    Thread-16 get sm
    Thread-17 get sm
    Thread-19 get sm
    Thread-20 get sm
    Thread-18 get sm
    macname@MacdeMacBook-Pro py %
     
     
     
     
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    2020软件工程作业02
    自我介绍
    Requests的使用
    爬虫基本原理
    2019春总结作业
    十二周作业
    十一周作业
    第十周作业
    intellij idea 的全局搜索快捷键方法
    Oracle多表关联
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14192180.html
Copyright © 2011-2022 走看看