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

本文详细介绍了Python中Semaphore对象的工作原理,包括其计数器管理、acquire和release方法的使用,以及如何通过示例代码展示线程间的同步控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

转载于:https://www.cnblogs.com/thunderLL/p/9852687.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值