首页 > 编程语言 > 详细

python,信号量,semaphore

时间:2019-12-15 12:06:06      阅读:107      评论:0      收藏:0      [点我收藏+]

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‘

python,信号量,semaphore

原文:https://www.cnblogs.com/iceberg710815/p/12043507.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!