I am very confused about the usage of Barrier

I was searching for something like wait group from golang in the std rust library. I came across with barrier but im confused about the usage of it. In golang the waitgroup has add and wait methods which increments and decrements the internal counter. However the Barrier has only wait method, so , how does it know about the threads and the example in the std docs pushed the ThreadHandles into a vector then call join on them. This was the most confusing thing for me because this could simply work without using barrier as well.

If you explain what you want to do, we might be able to recommend a Rust synchronization primitive that does that.

I am writing multithreaded tests what i want to do run a bunch of things in paralel on my module then when they all complete check the internal state if there were any concurrency bugs.I actually achieved this using a vec and pushing handles inside then calling join on them as in the std docs.
I just wanted to understand what is the purpose of barrier. @jethrogb

The purpose of the barrier is written directly at the top of the documentation for it:

A barrier enables multiple threads to synchronize the beginning of some computation.

It is not for some other thread to wait on a bunch of others to complete, it is for a bunch of threads to do something all at once, exactly when whichever is the last of threads reports being ready to start.

i see so the initial number provided is the one that barrier uses to understand which of the threads is the last one right ?

It is basically a semaphore that starts at some positive value and that you can only decrement. When a thread calls wait, the counter is decremented; if it's still nonzero, the call blocks. Once one thread, calling wait, causes the counter to reach zero, all the threads waiting on the barrier get released.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.