How to Implement Graceful Shutdown in Rust Servers

Web
Implement graceful shutdown in Rust servers by using an AtomicBool flag to signal threads to exit their loops cleanly upon receiving a termination signal.

Implement graceful shutdown by capturing the SIGINT signal, setting a shared AtomicBool flag, and having your server threads check this flag to exit their loops cleanly.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::Duration;

fn main() {
    let shutdown = Arc::new(AtomicBool::new(false));
    let shutdown_clone = shutdown.clone();

    // Simulate server thread
    thread::spawn(move || {
        while !shutdown_clone.load(Ordering::SeqCst) {
            // Do work
            thread::sleep(Duration::from_millis(100));
        }
        println!("Server thread shutting down gracefully.");
    });

    // Wait for Ctrl+C (SIGINT)
    let _ = std::io::stdin().read_line(&mut String::new());
    shutdown.store(true, Ordering::SeqCst);
    println!("Shutdown signal received.");
}