Categories: python

Barrier Object in Python

  • Barrier object in Python is used to synchronize the execution of multiple threads.
  • When a thread reaches a barrier point, it calls the wait() function, and the barrier keeps track of the number of threads that have reached the barrier.
  • When the number of threads that have reached the barrier is equal to the number of threads for which the barrier was initialized, all the threads are simultaneously released and can proceed with the execution.
  • Barriers can be used for different purposes, such as combining the output of multiple threads or synchronizing access to shared resources. For example, you could use a barrier to wait for all threads to finish processing a task before combining their results, or to ensure that a shared resource is only accessed by one thread at a time.
  • Barriers can be reused multiple times for the exact same number of threads that it was initially initialized for. The Barrier object keeps track of how many threads have reached the barrier, so it can be used again to wait for the same number of threads.
Syntax of the Barrier class:
threading.Barrier(parties, action=None, timeout=None)

Where parties specify the number of threads waiting at the barrier, action specifies a function that will be executed by any waiting thread, and timeout specifies a timeout value in seconds after which the barrier will be released from all waiting threads.

Functions provided by Barrier class:

The threading module’s Barrier class in Python provides several methods for interacting with and controlling the barrier. Here is a list of some of the most commonly used methods:

  • __init__(parties, action=None, timeout=None): Initializes the barrier with the specified number of parties (threads) and an optional action to be executed when the barrier is broken.
  • wait(timeout=None): Wait for other threads to arrive at the barrier. If the specified number of threads have not yet arrived at the barrier, the calling thread will be blocked. A timeout can also be provided.
  • broken(): Return True if the barrier is in a broken state.
  • reset(): Reset the barrier to its initial state.
  • abort(): Place the barrier into a ‘broken’ state and wake up all threads waiting on the barrier.

Additionally, the Barrier class also provides a property parties,

  • parties: The number of threads required to trip the barrier.
  • n_waiting: The number of threads currently waiting at the barrier.

These methods allow you to control the behavior of the barrier, wait for other threads to arrive, check the state of the barrier, and reset or break the barrier.

Example:
from threading import Barrier
import time

def thread_1(barrier):
    print("Thread 1: before barrier")
    barrier.wait()
    print("Thread 1: after barrier")

def thread_2(barrier):
    print("Thread 2: before barrier")
    barrier.wait()
    print("Thread 2: after barrier")

def thread_3(barrier):
    print("Thread 3: before barrier")
    barrier.wait()
    print("Thread 3: after barrier")

barrier = Barrier(3)

t1 = threading.Thread(target=thread_1, args=(barrier,))
t2 = threading.Thread(target=thread_2, args=(barrier,))
t3 = threading.Thread(target=thread_3, args=(barrier,))

t1.start()
t2.start()

# check if barrier is broken or not
print(barrier.broken()) #False

# check number of threads waiting at the barrier
print(barrier.n_waiting) # 0

# wait for t3 to reach the barrier
t3.start()

# check number of threads waiting at the barrier
print(barrier.n_waiting) # 2

# wait for all threads to reach the barrier
barrier.wait()

# check if barrier is broken or not
print(barrier.broken()) #False

t1.join()
t2.join()
t3.join()

In this example, the Barrier class is used to synchronize the execution of three threads. Each thread calls the wait() function when it reaches the barrier, and the barrier keeps track of the number of threads that have reached it. When all three threads have reached the barrier, they are simultaneously released and can proceed with their execution.

In this example, The function broken() is used to check the state of barrier. n_waiting property is used to check the number of threads waiting at the barrier.

Note: also read about Condition object in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 day ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago