Threads – When to Use Barrier in Multithreading

concurrencymultithreadingparallelismpythonsynchronization

Using python syntax,

threading.Barrier(NUM_THREADS) establishes a control point and all participating threads block until all of the participating “parties” have reached that point. It lets threads start up separately and then pause until they are all ready to proceed.

Can someone explain, a real time scenario(multi-thread), on usage of barrier?

Best Answer

Barriers are used to make multiple threads within the same program do something in a synchronized fashion.

The real-world analog would be the starting gate at a horse race. Ten horses in a race won't arrive at the gate at the same time, but it isn't until all ten of them have entered the gate and are ready to race does the gate open and each horse starts its race. (Starting gates are also called starting barriers because they were barriers rather than gates, which might be where the threading construct got its name.)

Threading's barrier does the same thing. In a system where each thread has a function and all must be ready before any starts operating, the way to enforce that is have the threads initialize and then meet at a barrier. You might see this in the system that runs the engine in your car, where the thread overseeing ignition wouldn't want to operate until it can be sure the threads that handle the throttle and crank position sensors are ready to provide useful data.

Related Topic