python,信号量,semaphore

python中的信号量,是通过定义semaphore对象,控制同时可以运行的线程的数量,同时也是一种锁,下面的代码演示了信号量的应用

import threading,time
class MyThread(threading.Thread):
    def __init__(self,name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        semaphore.acquire()
        print(self.name)
        time.sleep(3)
        semaphore.release()

if __name__ == "__main__":
    semaphore = threading.BoundedSemaphore(5)
    for i in range(40):
        t = MyThread('Alex')
        t.start()

这段代码运行后,通过semaphore实现了同时可以允许5个线程同步运行,每隔3秒显示5个'Alex'

猜你喜欢

转载自www.cnblogs.com/iceberg710815/p/12043507.html