semaphore信号量锁 -- 用来控制线程并发数

  • 信号量是一个变量,控制着对公共资源或者临界区的访问。信号量维护着一个计数器,指定可同时访问资源或者进入临界区的线程数。每次有一个线程获得信号量时,计数器-1。若计数器为0,其他线程就停止访问信号量,直到另一个线程释放信号量。
import threading,time
class MyThread(threading.Thread):
    def run(self):
        if semaphore.acquire():
            print(self.name)
            time.sleep(5)
            semaphore.release()
if __name__ == "__main__":
    semaphore = threading.Semaphore(5)
    thrs = []
    for i in range(100):
        thrs.append(MyThread())
    for t in thrs:
        t.start()

 

posted @ 2018-09-03 13:25  运维00001  阅读(331)  评论(0编辑  收藏  举报