Barrier Object

Barrier

The Barrier object allows us to make two or more threads wait till a certain condition has been met. We achieve this using the wait() function, and each of the threads tries to pass over the wait() function but all attempts to pass over it will be blocked till all of the threads have come to the wait() function.

Barrier Object

The syntax of the Barrier object is:

  • <variable_name> = threading.Barrier(parties, timeout=None)
    • parties – Represent the number of threads that are waiting at the Barrier.
    • timeout – Represent the number of seconds after which the Barrier will be lifted for all waiting threads.

Let’s look at a simple example:

import threading, time



# Object of Barrier Class
barrier_object = threading.Barrier(parties=2, timeout=None)

def sing_anthem():
    print("\nPlease stand up for the anthem")
    print("--Singing--")
    time.sleep(3)  # waiting for anthem to finish
    print("Finished singing the anthem\n")

def student_arrival():
    print("Students have come")
    sing_anthem()  # begin the anthem
    barrier_object.wait()  # wait for anthem to finish
    print("Students have sat down")

def teacher_arrival():
    print("Teacher has come")
    barrier_object.wait()  # wait for anthem to finish
    print("Teacher has started teaching")


teacher_variable = threading.Thread(name="Teacher Thread", target=teacher_arrival)
student_variable = threading.Thread(name="Student Thread", target=student_arrival)

teacher_variable.start()
student_variable.start()

We get the output as:

We created three functions for the above program. The first function sings the national anthem, whereas the second and third functions are for students and teachers respectively. In the student and teacher functions, we added the wait() function of the Barrier class.

Now, when we access these functions in threads, if one function reaches the wait before the other, it will stop executing till the other function also reaches the wait. In our program, the teacher thread reaches wait before the student thread. The teacher thread stops for 3 seconds and by then the student thread also reaches wait.

The student thread takes 3 seconds to reach the wait as we have given 3 seconds of sleeping time to finish singing the national anthem.

Let’s explore the functions offered by the Object Class:

FUNCTION 1: wait(timeout=None)

The wait() function makes a thread wait till all of the other threads have also reached the wait() function. 

If we specify a timeout and the timeout expires before all the threads can pass the barrier, then Python will raise the ‘BrokenBarrierError’. If we wish to use a timeout, we need to set engulf this code in a try-except statement.

This function will return the number of parties that are yet to arrive at the barrier. If the function returns a 0, it signifies that the current thread was the last one to arrive at the barrier. This is useful in scenarios when we want the last thread to do a certain task.

In our example we can see that the last program the last line is from the teacher function, this implies that the Teacher Thread reaches last so we can add features to the program accordingly. Re-writing our Teacher function would look like this:

def teacher_arrival():
    print("Teacher has come")
    remaining = barrier_object.wait()  # wait for anthem to finish
    print("Teacher has started teaching")

    # if last thread
    if remaining == 0:
        print("Class is over")
        print("Teacher cleans the blackboard")

 

 

FUNCTION 2: n_waiting

This gives us the number of threads that are waiting, and from our earlier example we can re-write the student function as:

def student_arrival():
    print("Students have come")
    sing_anthem()  # begin the anthem
   
    # See how many other threads are waiting
    print("Number of threads waiting:", barrier_object.n_waiting)
   
    barrier_object.wait()  # wait for anthem to finish
    print("Students have sat down")

FUNCTION 3: parties

This gives us the number of threads needed to overcome the barrier.

# See how many threads are required to pass the barrier
print("Number of threads required:", barrier_object.parties

FUNCTION 4: abort()

If called moves a barrier into a broken state. Now all of the other waiting threads will receive an error, specifically the ‘BrokenBarrierError’. This is beneficial when we want to avoid deadlocking.

 

FUNCTION 5: broken

This checks if a barrier is in a broken state or not.

What have we learned?

  • What is the use of the Barrier object?
  • Which function can be used to make a thread wait?
  • What does the wait() function return and how can we make use of it?
  • How to properly use the timeout parameter of the wait() function?
  • How do ‘parties’ and ‘n_waiting’ differ?
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments