python多线程-Semaphore(

发布时间:2019-03-22 21:57:09编辑:auto阅读(1716)

    Semaphore(value=1)

    Semaphore对象内部管理一个计数器,该计数器由每个acquire()调用递减,并由每个release()调用递增。计数器永远不会低于零,当acquire()发现计数器为零时,线程阻塞,等待其他线程调用release()
    Semaphore对象支持上下文管理协议。
    方法:
    acquire(blocking=True, timeout=None)
    获取信号。
    blocking=True时:如果调用时计数器大于零,则将其减1并立即返回。如果在调用时计数器为零,则阻塞并等待,直到其他线程调用release()使其大于零。这是通过适当的互锁来完成的,因此如果多个acquire()被阻塞,release()将只唤醒其中一个,这个过程会随机选择一个,因此不应该依赖阻塞线程的被唤醒顺序。
    返回值为True
    blocking=False时,不会阻塞。如果调用acquire()时计数器为零,则会立即返回False.
    如果设置了timeout参数,它将阻塞最多timeout秒。如果在该时间段内没有获取锁,则返回False,否则返回True

    release()
    释放信号,使计数器递增1。当计数器为零并有另一个线程等待计数器大于零时,唤醒该线程。

    BoundedSemaphore(value=1)

    实现有界信号对象。有界信号对象确保计数器不超过初始值value,否则抛出ValueError
    大多数情况下,该对象用于保护有限容量的资源。

    栗子:

    # -*- coding:utf-8 -*-
    import threading
    import time
    
    
    sem = threading.Semaphore(3)
    
    
    class DemoThread(threading.Thread):
    
        def run(self):
            print('{0} is waiting semaphore.'.format(self.name))
            sem.acquire()
            print('{0} acquired semaphore({1}).'.format(self.name, time.ctime()))
            time.sleep(5)
            print('{0} release semaphore.'.format(self.name))
            sem.release()
    
    
    if __name__ == '__main__':
        threads = []
        for i in range(4):
            threads.append(DemoThread(name='Thread-' + str(i)))
    
        for t in threads:
            t.start()
    
        for t in threads:
            t.join()

    运行结果:

    Thread-0 is waiting semaphore.
    Thread-0 acquired semaphore(Thu Oct 25 20:33:18 2018).
    Thread-1 is waiting semaphore.
    Thread-1 acquired semaphore(Thu Oct 25 20:33:18 2018).
    Thread-2 is waiting semaphore.
    Thread-2 acquired semaphore(Thu Oct 25 20:33:18 2018).
    Thread-3 is waiting semaphore.
    Thread-0 release semaphore.
    Thread-3 acquired semaphore(Thu Oct 25 20:33:23 2018).
    Thread-1 release semaphore.
    Thread-2 release semaphore.
    Thread-3 release semaphore.

    可以看到Thread-3是在Thread-0释放后才获得信号对象。

关键字

上一篇: 切片

下一篇: Python的scrapy之爬取6毛小说