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 %
     
     
     
     
     
     
     
     
     
     
     
     
     

  • 相关阅读:
    函数库:静态库和动态库
    预处理
    共用体、大端小端的判断、枚举
    结构体内存对齐及大小的判断
    内存的管理方式
    指针的高级应用
    H5+css3属性随笔
    项目实战——仿360囧图
    利用css3的动画实现图片轮播
    了解HTML5大纲算法
  • 原文地址:https://www.cnblogs.com/sea-stream/p/14192180.html
Copyright © 2011-2022 走看看