Home
Map
Barrier Example (thread)Use the Barrier type to have all threads wait for a certain point to be reached before any can continue.
Rust
This page was last reviewed on Dec 15, 2023.
Barrier. Suppose we have a Rust program that has many threads that are working to complete a task. But a certain part of the task must be complete before any thread may continue.
With Barrier, part of the standard library, we can force all threads to wait for a certain point to be reached. We use the wait() function. A Mutex and Condvar is internally used in the Barrier.
Mutex
Example. When using threads in Rust, we must add code to set up the threads. We need to create an Arc and clone it in a vector, then spawn a thread for each vector element.
Step 1 We create a Barrier, and pass it the thread count where it will be used to block all threads. We place it in an Arc.
Arc
Step 2 We loop over our vector that contains an Arc of the Barrier in each element, and spawn a thread for each element.
Step 3 We run some code in each thread. In the middle, we have a wait() call that calls the Barrier wait function.
Step 4 We join all the threads together—this step is needed to ensure the program does not exit too early.
use std::sync::*; use std::thread; fn main() { // Step 1: place a Barrier in an Arc, and clone one Arc into each element of an array. let thread_count = 8; let shared = Barrier::new(thread_count); let mut v = vec![]; let arc = Arc::new(shared); for _ in 0..8 { v.push(arc.clone()); } // Step 2: loop over vector elements, and create thread for each element. let mut children = vec![]; for item in v { children.push(thread::spawn(move || { // Step 3: run some code before the wait() function is called on the Barrier, and some after. println!("Part A"); item.wait(); println!("Part B"); })); } // Step 4: join all threads. for child in children { child.join().ok(); } }
Part A Part A Part A Part A Part A Part A Part A Part A Part B Part B Part B Part B Part B Part B Part B Part B
Barrier results. We can see that the "Part A" print statements are all before the "Part B" statements. Each thread blocks until all the "Part A" statements are written.
Summary. Barriers are useful for many multi-threaded Rust programs. Suppose we have many worker threads, but one operation must be complete before the next can begin—Barrier is perfect here.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 15, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.