4

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?

7
  • 2
    You've already stated the criteria in your question: when you need a control point where all participating threads block until all of the participating “parties” have reached that point; a control point that lets threads start up separately and then pause until they are all ready to proceed. Commented Jul 22, 2017 at 18:22
  • @RobertHarvey Example would help me, visualize this context Commented Jul 22, 2017 at 18:24
  • 1
    I found many such examples in a Google search. Have you checked out those examples yet? Commented Jul 22, 2017 at 18:26
  • This question would work better if rephrased in the same vein as What is a thread pool?
    – Blrfl
    Commented Jul 22, 2017 at 18:29
  • 1
    What do you mean by "incorrect?" That example comes directly from the Python Software Foundation, so I very much doubt that it is incorrect. Commented Jul 22, 2017 at 18:33

2 Answers 2

4

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.

2

An example usage is something like a worker pool where you would want all of your workers to report ready before sending them work. Or something like the subsystems of a game loading up in parallel. Or the map steps in map-reduce...

It's just a tool.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.