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

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

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

The balance is in a `Mutex<u32>`, only reachable through the guard `lock()` returns, which unlocks when dropped. Locking it again from its owner panics, as it would hand out the data twice: `ReentrantMutex` is the one its owner may lock again, and shares its data instead. The race without a lock is staged with an atomic, read and written in two steps.

Run:

`pbl samples samples/rust/kernel/mutex`

Boards:

every board

## Sources

src/lib.rs

```
#![no\_std]use core::cell::Cell;use core::sync::atomic::{AtomicU32, Ordering};use core::time::Duration;use pebbleos::sync::{Mutex, ReentrantMutex, Semaphore};use pebbleos::thread::{self, Priority, Thread};use pebbleos::time::Timeout;use pebbleos::{Result, println};const DEPOSITS: u32 = 100;const WORKER\_PRIO: Priority = Priority::MAIN.lower(1);// Atomic, so each access alone is safe, but a read and a write are two of// them, which another thread can come in between.static UNLOCKED\_BALANCE: AtomicU32 = AtomicU32::new(0);// The data is only reached through the lock.static BALANCE: Mutex\<u32\> = Mutex::new(0);// Its owner may lock it again, e.g. in a function called with it held.static LEDGER: ReentrantMutex\<Cell\<u32\>\> = ReentrantMutex::new(Cell::new(0));static HOLDER\_RELEASE: Semaphore = Semaphore::new(0, 1);static THREAD\_A: Thread = Thread::new();static THREAD\_B: Thread = Thread::new();fn deposit\_unlocked() {let balance = UNLOCKED\_BALANCE.load(Ordering::Relaxed);// Stands for being preempted between the read and the write.thread::yield\_now();UNLOCKED\_BALANCE.store(balance + 1, Ordering::Relaxed);}fn deposit() {let mut balance = BALANCE.lock();let before = \*balance;thread::yield\_now();\*balance = before + 1;}fn run\_depositors(f: fn()) -\> Result\<()\> {let depositor = move || {for \_ in 0..DEPOSITS {f();}};THREAD\_A.spawn(c"a", WORKER\_PRIO, depositor)?;THREAD\_B.spawn(c"b", WORKER\_PRIO, depositor)?;THREAD\_A.join(Duration::from\_secs(1))?;THREAD\_B.join(Duration::from\_secs(1))}#[pebbleos::main]fn main() -\> Result\<()\> {run\_depositors(deposit\_unlocked)?;println!("main: without the lock, balance is {} after {} deposits",UNLOCKED\_BALANCE.load(Ordering::Relaxed),2 \* DEPOSITS);run\_depositors(deposit)?;println!("main: with the lock, balance is {} after {} deposits",\*BALANCE.lock(),2 \* DEPOSITS);// A lock held elsewhere for long is better waited for with a limit.THREAD\_A.spawn(c"holder", WORKER\_PRIO, || {let \_balance = BALANCE.lock();let \_ = HOLDER\_RELEASE.take(Timeout::FOREVER);})?;thread::sleep(Duration::from\_millis(10));let ret = BALANCE.lock\_timeout(Duration::from\_millis(10)).map(drop);println!("main: lock held by another thread, 10 ms wait returns {ret:?}");HOLDER\_RELEASE.give();drop(BALANCE.lock());let outer = LEDGER.lock();let inner = LEDGER.lock();inner.set(inner.get() + 1);drop(inner);println!("main: locked twice, unlocked once, still the owner: {}",if LEDGER.is\_owner() { "yes" } else { "no" });drop(outer);println!("Sample done");Ok(())}
```

## Output

```
main: without the lock, balance is \d+ after 200 deposits
main: with the lock, balance is 200 after 200 deposits
main: lock held by another thread, 10 ms wait returns Err\(EAGAIN\)
main: locked twice, unlocked once, still the owner: yes
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/mutex.md](https://github.com/coredevices/pebbleos/blob/7753e801d93d20f2d37534ce2fa69d9952015237/docs/samples/rust/kernel/mutex.md).
