Stop Worker Loop With AtomicBool Flag

An Arc-shared AtomicBool lets the main thread flip a stop flag while the worker spins on load, and join confirms the shutdown before the process exits.

RustResilience

Code

rustsnippet
26 lines
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;

fn main() {
    // Arc 共享的 AtomicBool:多 worker 场景对每个线程 clone 一份即可,
    // load/store 都是原子操作,不需要加锁
    let stop = Arc::new(AtomicBool::new(false));

    let worker = {
        let stop = Arc::clone(&stop);
        thread::spawn(move || {
            for batch in 1..=3 {
                println!("batch {batch} done");
            }
            while !stop.load(Ordering::Relaxed) {
                thread::yield_now(); // 空转等待停止标志翻转
            }
            println!("worker saw stop flag, exiting");
        })
    };

    stop.store(true, Ordering::Relaxed); // 一处写入,共享方都能看到
    worker.join().expect("worker panicked");
    println!("joined cleanly");
}

How it works

Stop Worker Loop With AtomicBool Flag reduces to the function main.

Iteration happens inside for batch in 1..=3 — everything outside it runs once.

Caveats

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

The main signature reads fn main()

The run emits 3 labeled sections — batch, worker saw stop flag, exiting, joined cleanly — one per step.

The key statements, annotated

thread::spawn(move || {
    for batch in 1..=3 {
        println!("batch {batch} done");
    }
    while !stop.load(Ordering::Relaxed) {
        thread::yield_now(); // 空转等待停止标志翻转
    }
    println!("worker saw stop flag, exiting");
})

Interactive Tools for This Topic

FAQ

What does Stop Worker Loop With AtomicBool Flag print when run?
Running the file directly is enough — expect labeled output lines such as `batch`, `worker saw stop flag, exiting`, `joined cleanly`.