当前位置: 移动技术网 > IT编程>脚本编程>Python > python多线程-Semaphore(信号对象)

python多线程-Semaphore(信号对象)

2018年10月26日  | 移动技术网IT编程  | 我要评论

兰欣娜,成也萧何败萧何,李若含

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释放后才获得信号对象。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网