Python中的屏障对象
屏障提供了一种Python同步技术,多个线程可以等待一组活动中的某个点,然后一起继续执行。
要定义屏障对象,可以使用“threading.Barrier”。
threading.Barrier(parties, action = None, timeout = None)
其中,
parties = 线程数
action = 当线程被释放时,由其中一个线程调用。
timeout = 默认超时值。如果wait()没有指定超时值,则使用此超时值。
屏障类使用以下方法。
| 序号 | 方法及描述 |
|---|---|
| 1 | parties 到达公共屏障点所需的线程数。 |
| 2 | n_waiting 在公共屏障点等待的线程数 |
| 3 | broken 布尔值,True - 如果屏障处于中断状态,否则为False。 |
| 4 | wait( timeout = None) 等待直到收到通知或超时。如果调用线程在调用此方法时未获取锁,则会引发运行时错误。 此方法释放底层锁,然后阻塞,直到被另一个线程对同一条件变量的notify()或notify_all()方法调用唤醒,或者直到可选超时发生。一旦被唤醒或超时,它会重新获取锁并返回。 当存在*timeout*参数且不为**None**时,它应该是浮点数,以秒(或其分数)指定操作的超时时间。 |
| 5 | reset() 将屏障设置为默认状态,即空状态。等待它的线程将收到BrokenBarrierError。 |
| 6 | Abort() 这会将屏障置于中断状态。这会导致所有活动线程或将来对wait()的任何调用都失败并出现BrokenBarrierError。 |
barrierThread.py
from random import randrange
from threading import Barrier, Thread
from time import ctime, sleep
num = 4
# 4 threads will need to pass this barrier to get released.
b = Barrier(num)
names = ['India', 'Japan', 'USA', 'China']
def player():
name = names.pop()
sleep(randrange(2, 5))
print('%s reached the barrier at: %s \n' % (name, ctime()))
b.wait()
threads = []
print("Race starts now…")
for i in range(num):
threads.append(Thread(target=player))
threads[-1].start()
"""
Below loop enables waiting for the threads to complete before moving on with the main script.
"""
for thread in threads:
thread.join()
print("All Reached Barrier Point!")结果
Race starts now… India reached the barrier at: Fri Jan 18 14:07:44 2019 China reached the barrier at: Fri Jan 18 14:07:44 2019 Japan reached the barrier at: Fri Jan 18 14:07:46 2019 USA reached the barrier at: Fri Jan 18 14:07:46 2019 All Reached Barrier Point!
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP