---
title: "Barrier in Rust"
canonical_url: https://developer.repebble.com/pebbleos/docs/samples/rust/kernel/classic/barrier/
last_updated: 2026-11-18
sdk_version: 4.44
---
# Barrier in Rust

Source: https://developer.repebble.com/pebbleos/docs/samples/rust/kernel/classic/barrier/

The [barrier sample](https://developer.repebble.com/pebbleos/docs/samples/kernel/classic/barrier.md) written in [Rust](https://developer.repebble.com/pebbleos/docs/development/build_system/rust.md), on the `pebbleos` crate.

The count of arrivals is in a `Mutex`, whose guard is dropped before waiting at the gate.

Run:

`pbl samples samples/rust/kernel/classic/barrier`

Boards:

every board

## Sources

src/lib.rs

```
#![no\_std]use core::time::Duration;use pebbleos::sync::{Mutex, Semaphore};use pebbleos::thread::{self, Priority, Thread};use pebbleos::time::Timeout;use pebbleos::{Result, println};const NUM\_WORKERS: usize = 3;/// A point no thread passes until all of them have reached it.struct Barrier {waiting: Mutex\<usize\>,gate: Semaphore,parties: usize,}impl Barrier {const fn new(parties: usize) -\> Barrier {Barrier {waiting: Mutex::new(0),gate: Semaphore::new(0, parties as u32),parties,}}fn wait(&self) {let mut waiting = self.waiting.lock();\*waiting += 1;if \*waiting == self.parties {// The last one in lets the others through, and leaves the barrier// ready for another round.for \_ in 1..self.parties {self.gate.give();}\*waiting = 0;return;}drop(waiting);let \_ = self.gate.take(Timeout::FOREVER);}}struct Stats {ready: usize,passed: usize,passed\_early: usize,}static START\_LINE: Barrier = Barrier::new(NUM\_WORKERS);static STATS: Mutex\<Stats\> = Mutex::new(Stats {ready: 0,passed: 0,passed\_early: 0,});static WORKERS: [Thread; NUM\_WORKERS] = [const { Thread::new() }; NUM\_WORKERS];fn worker(id: usize) {// Getting ready takes each worker a different time.thread::sleep(Duration::from\_millis(20 \* (id as u64 + 1)));STATS.lock().ready += 1;println!("worker {id}: ready");START\_LINE.wait();let mut stats = STATS.lock();if stats.ready != NUM\_WORKERS {stats.passed\_early += 1;}stats.passed += 1;}#[pebbleos::main]fn main() -\> Result\<()\> {for (id, t) in WORKERS.iter().enumerate() {t.spawn(c"worker", Priority::MAIN.lower(1), move || worker(id))?;}for t in &WORKERS {t.join(Duration::from\_secs(1))?;}let stats = STATS.lock();println!("main: {} past the barrier, {} of them before the last was ready",stats.passed, stats.passed\_early);println!("Sample done");Ok(())}
```

## Output

```
worker \d: ready
worker \d: ready
worker \d: ready
main: 3 past the barrier, 0 of them before the last was ready
Sample done
```

Generated from PebbleOS [7753e801d](https://github.com/coredevices/pebbleos/commit/7753e801d93d20f2d37534ce2fa69d9952015237). This page is maintained in the pebbleos repository: [docs/samples/rust/kernel/classic/barrier.md](https://github.com/coredevices/pebbleos/blob/7753e801d93d20f2d37534ce2fa69d9952015237/docs/samples/rust/kernel/classic/barrier.md).
