CyclicBarrier is a synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point before proceeding. This is particularly useful in scenarios where multiple threads need to coordinate their progress, such as in simulations, parallel computations, or any other type of concurrent programming.
When the threads reach the barrier, they are released all at once, allowing them to continue their execution in a coordinated fashion. If a thread arrives at the barrier and there are still other threads that have not yet reached it, that thread will wait until the others arrive.
It's important to note that the barrier can be reset after all threads have crossed it, allowing it to be reused. However, exceptions can occur if one of the waiting threads is interrupted or times out, which can lead to the barrier being tripped and the threads being released prematurely.
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
public class CyclicBarrierExample {
private static final int NUMBER_OF_THREADS = 3;
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(NUMBER_OF_THREADS, () -> {
System.out.println("All threads reached the barrier, proceeding...");
});
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
final int threadId = i;
new Thread(() -> {
try {
System.out.println("Thread " + threadId + " is doing some work...");
Thread.sleep((long) (Math.random() * 1000)); // simulate work
System.out.println("Thread " + threadId + " is waiting at the barrier");
barrier.await(); // wait for others at the barrier
System.out.println("Thread " + threadId + " has crossed the barrier");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?