Barrier Objects:

It is there for waiting for a finite number of threads to complete execution before executing any particular thread. Each thread calls upon the wait() function when it reaches the barrier. The barrier keeps track of the number of wait() calls. When the number of wait() calls goes beyond the number for which the barrier was initialize then, the barrier will give way to waiting threads to execute. All threads at this point of execution are release simultaneously in python while using it for data science.

We can use barrier objects for synchronizing access between threads. But in general, barriers are there for combining the output of threads. Barrier object can be reused for any number of times for the exact same number of threads for which we initialise it initially.

Initializing a Barrier:

We can initialise it using threading.Barrier class. The number which is there within the parenthesis denotes the number of threads the barrier has to wait.


Below is an example illustrating the barrier object:

python data science

Function calls in relation with threading.Barrier class:
  1. Checking state of the barrier: It is a Boolean value which returns True f the barrier is in broken state.

Syntax:  barrier.broken

  1. Parties: It denotes the number of threads required to pass the barrier.

Syntax: barrier.parties

  1. Aborting barrier: It puts the barrier in a broken state. Because of this all active and future calls to wait() fails and a BrokenBarrierError is shown. This function comes in handy when it is required to skip the condition of deadlocking during the execution of a program.

Syntax: barrier.abort()

  1. Resetting the barrier: It returns the barrier to the default, i.e., to an empty state. All threads which are waiting will get a BrokenBarrierError once this function is there.

Syntax: barrier.reset()

  1. wait: When all threads waiting at the barrier use this function, they are all simultaneously release. In case a timeout is available, it is there in preference to any which was supply to class constructor.

The values that we return are in the range of 0 to -1 for parties. They are different for each thread. In a situation where the call times out then, the barrier is put into a broken state.

Syntax: barrier.wait(timeout = None)

  1. n_waiting: It shows the number of threads waiting at the barrier currently.

Syntax: barrier.n_waiting

An example will make all things clear.

If you want to learn more about it in python for data science, then you can check this and this as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.