python线程安全的计数器_python多线程-Semaphore(信号对象)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值