Barrier Objects in Python with Example

In this tutorial, we will learn what are barrier objects and how to create them in Python. We will also see an example of how to use them in Python.

Barrier Objects in Python

Barrier objects are used to provide a barrier for the execution of threads. When we create a barrier object, we specify a variable called ‘number_of_threads’. When a wait() function is called using this barrier object, the thread which called this function is going to wait until the number of threads which called the wait() function is equal to ‘number_of_threads’. Once it becomes equal all the threads are going to be released from the waiting state.


barrier_object = threading.Barrier(number_of_threads, action = None, timeout = None)


from threading import Barrier, Thread
import time

def producer (barrier_object):
    print ("Producer producing...")
    print ("Produced\n")

def consumer (barrier_object):
    print ("Waiting to consume...")
    print ("Consumed")

if __name__ == '__main__':
    barrier_object = Barrier(2)
    s = Thread (target = producer, args = (barrier_object,))
    c = Thread (target = consumer, args = (barrier_object,))

In the above code, we imported Barrier from threading for creating barrier object, Thread to create threads and time to call sleep() function.

In the main, let us create a barrier object with ‘number_of_threads’ as 2. We shall also create 2 threads targeting to functions producer and consumer. When thread ‘s’ starts executing producer, we called wait() function using barrier object. So, this thread will be waiting. When thread ‘c’ starts executing consumer, we called wait() function using barrier object. So, this thread will also be waiting. Now, the total number of threads waiting is equal to 2 i.e., ‘number_of_threads’. So, all the threads waiting are released and execution resumes.


Producer producing...
Waiting to consume...

Also read, How to call a function after some interval in Python

Leave a Reply
