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

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

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

Each `Thread` is a static that owns its stack and runs a closure; `spawn()` fails while the previous one still runs, and `join()` waits for it to end.

Run:

`pbl samples samples/rust/kernel/threads`

Boards:

every board

## Sources

src/lib.rs

```
#![no\_std]use core::sync::atomic::{AtomicU32, Ordering};use core::time::Duration;use pebbleos::thread::{self, Priority, Thread};use pebbleos::{Result, println};const ROUNDS: u32 = 3;// main() runs at Priority::MAIN: one thread above it, two below.const URGENT\_PRIO: Priority = Priority::MAIN.raise(1);const PEER\_PRIO: Priority = Priority::MAIN.lower(1);static URGENT: Thread = Thread::new();static PING: Thread = Thread::new();static PONG: Thread = Thread::new();fn peer(rounds: &AtomicU32) {let me = thread::current();while rounds.load(Ordering::Relaxed) \< ROUNDS {println!("{}: round {}", me.name(), rounds.load(Ordering::Relaxed));rounds.fetch\_add(1, Ordering::Relaxed);// Threads of equal priority also take turns on every tick; yielding// does it now.thread::yield\_now();}}#[pebbleos::main]fn main() -\> Result\<()\> {static PING\_ROUNDS: AtomicU32 = AtomicU32::new(0);static PONG\_ROUNDS: AtomicU32 = AtomicU32::new(0);println!("main: creating a thread of higher priority");URGENT.spawn(c"urgent", URGENT\_PRIO, || {println!("urgent: preempted main, which is still inside spawn()");})?;println!("main: urgent has {}",if URGENT.is\_finished() {"ended"} else {"not ended"});PING.spawn(c"ping", PEER\_PRIO, || peer(&PING\_ROUNDS))?;PONG.spawn(c"pong", PEER\_PRIO, || peer(&PONG\_ROUNDS))?;println!("main: created two threads of lower priority, which wait for main to block");PING.join(Duration::from\_secs(1))?;PONG.join(Duration::from\_secs(1))?;println!("main: ping ran {} rounds, pong ran {} rounds",PING\_ROUNDS.load(Ordering::Relaxed),PONG\_ROUNDS.load(Ordering::Relaxed));println!("Sample done");Ok(())}
```

## Output

```
main: creating a thread of higher priority
urgent: preempted main, which is still inside spawn\(\)
main: urgent has ended
main: created two threads of lower priority, which wait for main to block
main: ping ran 3 rounds, pong ran 3 rounds
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/threads.md](https://github.com/coredevices/pebbleos/blob/7753e801d93d20f2d37534ce2fa69d9952015237/docs/samples/rust/kernel/threads.md).
