Rust, Software Development

Rust – Thread Synchronization using Barrier

Rust Thread Synchronization Barrier validate Email Regular Expressions check String Numeric display content array tuple hashmap vector
Photo by Mike from Pexels

This post is about Rust thread synchronization with Barrier using std::sync::Barrier which is part of Rust’s standard library. Therefore, we do not need external dependencies to make things work.

Basic Idea of Barrier

The basic idea of using barriers is to pause threads at a certain point until we reach a certain count of started and paused threads. Only then the “barrier” breaks and allows all the threads to proceed with the execution.

Rust Thread Synchronization Codes

The following codes use a Barrier and force all threads to wait. Then, once all the threads invoke the wait function, the barrier breaks and allow all the threads to continue processing.

The barrier waits for 5 threads in waiting mode before it allows them to proceed. Note that we also use Arc to wrap a Barrier instance. Then, use invoke the wait function on an Arc instance. When we invoke the wait function on an Arc instance, we increment the internal counter with the Barrier instance.

When we run the codes, we get the following output. Note that lines 6-10 are not guaranteed to be the same every time the codes run.

And that is how to implement Rust Thread synchronization using Barrier.

You Might Also Like