美文网首页python并发
04. 多线程之信号量(BoundedSemaphore类)

04. 多线程之信号量(BoundedSemaphore类)

作者: 花间派I风月 | 来源:发表于2020-05-04 21:44 被阅读0次
    1. 互斥锁同时只允许一个线程更改数据,而Semaphore是同时允许一定数量的线程更改数据 ,
    2. 比如酒店有5个房间,那最多只允许5个人开房,后面的人只能等里面有人出来了才能再进去。
    #!/usr/bin/env python
    # coding:utf-8
    
    import threading
    import time
    
    
    def work(num, _semaphore):
        _semaphore.acquire()
        time.sleep(1)
        print(f"run the thread:{num}")
        _semaphore.release()
    
    
    if __name__ == '__main__':
        semaphore = threading.BoundedSemaphore(5)
        for i in range(20):
            t = threading.Thread(target=work, args=(f't-{i}', semaphore))
            t.start()
        while threading.active_count() != 1:
            print(f'active_count: {threading.active_count()}')
        else:
            print('all threads done.')
    

    相关文章

      网友评论

        本文标题:04. 多线程之信号量(BoundedSemaphore类)

        本文链接:https://www.haomeiwen.com/subject/tplughtx.html