Barrier is one of the Python Synchronization Primitives with which multiple threads wait till a point in a set of activities and make progress together.
For example, When a team of pilgrims walks together to a place of worship - they may arrive in the next town at different times between 5 PM and 5.30 PM. However, since they are making the travel as a group - they can not start travelling from the next town until all their group members have arrived there.
The similar mechanism in a multithreaded computing environment is called a Barrier. For Example, Threads counting normal votes should not proceed with counting of special votes like postal votes and votes by Government Staff.In this scenario the threads that count normal votes wait till all the other threads complete counting normal votes.
- In Python, the class Barrier of the threading module provides Barrier objects. The threads call the wait() method of the Barrier Object once they are done with the specific task and wait for all other threads in the thread group to complete the specific task.
- Once all the threads have called wait(), the threads are released to make further progress.
- The timeout value provided while constructing the Barrier Object will be used for crossing the barrier. If the timeout happens first before the thread completes, then the thread will cross the barrier. Though we do not want a timeout in a voting thread, the below example has one for demonstration purposes.
Example of Barrier Objects in Python:
BarrierObject = Barrier(2, timeout=5)