Barrier Objects in Python
Last Updated :
14 Jul, 2017
Barrier objects in python are used to wait for a fixed number of thread to complete execution before any particular thread can proceed forward with the execution of the program. Each thread calls wait() function upon reaching the barrier. The barrier is responsible for keeping track of the number of wait() calls. If this number goes beyond the number of threads for which the barrier was initialized with, then the barrier gives a way to the waiting threads to proceed on with the execution. All the threads at this point of execution, are simultaneously released.
Barriers can even be used to synchronize access between threads. However, generally a barrier is used to combine the output of threads. A barrier object can be reused multiple times for the exact same number of threads that it was initially initialized for.
Initializing a barrier
A barrier can be initialized using threading.Barrier class as shown in the program below. The number within the parenthesis represents the number of the threads that the barrier should wait upon.
Syntax:
barrier = threading.Barrier(number_of_threads, action = None, timeout = None)
Create a barrier object for the number_of_threads. An action, when provided, is a callable to be called by one of the threads when they are released. timeout is the default timeout value if none is specified for the wait() method.
Python
import threading
barrier = threading.Barrier(3)
class thread(threading.Thread):
def __init__(self, thread_ID):
threading.Thread.__init__(self)
self.thread_ID = thread_ID
def run(self):
print(str(self.thread_ID) + "\n")
barrier.wait()
thread1 = thread(100)
thread2 = thread(101)
thread1.start()
thread2.start()
barrier.wait()
print("Exit\n")
Output:
100
101
Exit
Some common function calls related to threading.Barrier class are:
- Checking the state of the barrier:
broken: A boolean that is True if the barrier is in the broken state.
Syntax:
barrier.broken
- parties: The number of threads required to pass the barrier.
Syntax:
barrier.parties
- Aborting a barrier:
abort: Put the barrier into a broken state. This causes any active or future calls to wait() to fail with the BrokenBarrierError
Abort function calls on barrier are often required to skip the conditions of deadlocking during program execution.
Syntax:
barrier.abort()
- Resetting the barrier:
reset: Return the barrier to the default, empty state. Any threads waiting on it will receive the BrokenBarrierError exception.
Syntax:
barrier.reset()
- wait: Pass the barrier. When all the threads party to the barrier have called this function, they are all released simultaneously. If a timeout is provided, it is used in preference to any that was supplied to the class constructor.
The return value is an integer in the range 0 to parties – 1, different for each thread. If the call times out, the barrier is put into the broken state. This method may raise a BrokenBarrierError exception if the barrier is broken or reset while a thread is waiting.
Syntax:
barrier.wait(timeout = None)
- n_waiting: The number of threads currently waiting in the barrier.
Syntax:
barrier.n_waiting
Usually, when either a barrier object is reset or broken down, then the BrokenBarrierError exception is raised.
Here's a sample program to display how barriers are used in python
Python
# program to demonstrate
# barriers in python
import threading
barrier = threading.Barrier(3)
class thread(threading.Thread):
def __init__(self, thread_ID):
threading.Thread.__init__(self)
self.thread_ID = thread_ID
def run(self):
print(str(self.thread_ID) + "\n")
print("Parties = " + str(barrier.parties) + "\n")
print("n_waiting = " + str(barrier.n_waiting) + "\n")
barrier.wait()
thread1 = thread(100)
thread2 = thread(101)
thread1.start()
thread2.start()
barrier.wait()
print(str(barrier.broken) + "\n")
barrier.reset()
print("n_waiting after reset = " + str(barrier.n_waiting))
barrier.abort()
print("End")
Output:
100
101
Parties = 3
Parties = 3
n_waiting = 1
n_waiting = 1
False
n_waiting after reset = 0
End
Similar Reads
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python 3 basics Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the
10 min read
Learn Python Basics âPython is a versatile, high-level programming language known for its readability and simplicity. Whether you're a beginner or an experienced developer, Python offers a wide range of functionalities that make it a popular choice in various domains such as web development, data science, artificial in
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Iterate over a list in Python Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly.Example: Print all elements in the list one by one using for loop.Pythona = [1, 3, 5, 7, 9] # On each
3 min read