class threading.Barrier(parties, action=None, timeout=None)
Create a barrier object for parties number of threads. An action, when provided, is a callable to be called by one of the threads when they are released. timeout is the default timeout value if none is specified for the wait()
method.
-
wait(timeout=None)
-
Pass the barrier. When all the threads party to the barrier have called this function, they are all released simultaneously. If a timeout is provided, it is used in preference to any that was supplied to the class constructor.
The return value is an integer in the range 0 to parties – 1, different for each thread. This can be used to select a thread to do some special housekeeping, e.g.:
i = barrier.wait() if i == 0: # Only one thread needs to print this print("passed the barrier")
If an action was provided to the constructor, one of the threads will have called it prior to being released. Should this call raise an error, the barrier is put into the broken state.
If the call times out, the barrier is put into the broken state.
This method may raise a
BrokenBarrierError
exception if the barrier is broken or reset while a thread is waiting.
-
reset()
-
Return the barrier to the default, empty state. Any threads waiting on it will receive the
BrokenBarrierError
exception.Note that using this function may can require some external synchronization if there are other threads whose state is unknown. If a barrier is broken it may be better to just leave it and create a new one.
-
abort()
-
Put the barrier into a broken state. This causes any active or future calls to
wait()
to fail with theBrokenBarrierError
. Use this for example if one of the needs to abort, to avoid deadlocking the application.It may be preferable to simply create the barrier with a sensible timeout value to automatically guard against one of the threads going awry.
-
parties
-
The number of threads required to pass the barrier.
-
n_waiting
-
The number of threads currently waiting in the barrier.
-
broken
-
A boolean that is
True
if the barrier is in the broken state.
Please login to continue.