Code Example Template
use std::thread;
thread::spawn(move || {
    start_global_os_input_hook();
});

Deep-Dive System Documentation

Multi-Threading: OS Parallel Execution

When listening for operating system keyboard inputs or running continuous background micro-tasks, running them on the main UI thread will cause latency lag. Rust solves this by spawning physical, OS-scheduled execution threads.

Spawning a Thread

Use std::thread::spawn and pass a closure containing the thread's execution body:

use std::thread;
use std::time::Duration;

thread::spawn(|| {
    for i in 1..5 {
        println!("Background process tick: {}", i);
        thread::sleep(Duration::from_millis(10));
    }
});

The move Directive

Because threads execute in parallel, they might outlive the scope that spawned them. Therefore, you must use the move keyword to transfer complete ownership of captured variables into the thread's closure:

let active_profile = String::from("Vercel");

thread::spawn(move || {
    // Ownership of active_profile was moved into the thread!
    println!("Monitoring profile: {}", active_profile);
});

Performance Metrics

  • Resource Cost: Allocates standard OS thread stacks (typically 2MB on modern architectures).
  • Scheduling: Managed natively by the kernel scheduler, leveraging multi-core CPUs.

Quick Reference Guide

use std::thread;
thread::spawn(|| { println!("thread"); });