Barrier Objects in Python


Barrier provides one of the python synchronization technique with which single or multiple threads wait until a point in a set of activities and make progress together.

To define a barrier object, “threading. Barrier” is used.

threading.Barrier(parties, action = None, timeout = None)

Where,

  • parties = Number of threads

  • action = called by one of the threads when they are released.

  • timeout = Default timeout value. In case no timeout value is specified for the wait(), this timeout value is used.

Below mentioned methods are used by Barrier class.

Sr.NoMethod & Description
1parties
A number of threads required to reach the common barrier point.
2n_waiting
Number of threads waiting in the common barrier point
3broken
A boolean value, True- if the barrier is in the broken state else False.
4wait( timeout = None)
Wait until notified or a timeout occurs. If the calling thread has not acquired the lock when this method is called, a runtime error is raised.
This method releases the underlying lock and then blocks until it is awakened by a notify() or notify_all() method call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns.
When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof).
5reset()
Set or return the barrier to the default state .i.e. empty state. And threads waiting on it will receive the BrokenBarrierError.
6Abort()
This will put the barrier into a broken state. This causes all the active threads or any future calls to wait() to fail with the BrokenBarrierError.

barrierThread.py

 Live Demo

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!")

Result

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!

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

347 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements