• 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 %
     
     
     
     
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    activity 背景透明
    win系统注册缺少的库 32位系统 64位系统
    android 窗
    wireshark抓包分析
    juqery select 标签
    IOS开发应用之Quartz 2D学习指南
    为什么你总会觉得自己的产品不够好
    日志宝
    Android之Inflate()方法用途+setContentView和inflate区别
    Ralasafe
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14192180.html
Copyright © 2020-2023  润新知