Code Example Template
use std::sync::Arc;
let global_config = Arc::new(Config::load());
let worker_ref = Arc::clone(&global_config);

Deep-Dive System Documentation

Arc: Atomic Shared References

Standard pointers like Rc<T> (Reference Counted) keep track of shared heap values by modifying increment ticks on copy. However, Rc is not thread-safe. If multiple threads increment the count concurrently, the counters can corrupt.

Arc<T> stands for Atomic Reference Counted. It uses CPU atomic operations (lock-free assembly signals) to safely manage reference updates across threads.

Sharing Configuration Across Thread Handlers

In desktop macro utilities, the active configuration is loaded once and shared across background keyboard hooks and UI workers:

use std::sync::Arc;
use std::thread;

let global_config = Arc::new(Config::load());

// Spawn keyboard hook worker thread
let hook_config = Arc::clone(&global_config); // Increments atomic counter
thread::spawn(move || {
    let _ = hook_config.get_shortcuts();
});

Performance Metrics

  • Read Cost: Zero-lock read-only access.
  • Clone Cost: Minor lock-free atomic increment. Extremely performant for thread pooling.
  • Write Cost: Arc is strictly read-only by default. For write access across threads, it must be paired with interior mutability (such as Mutex).

Useful Methods

Arc::new(value: T) -> Arc<T>

Constructs a new Arc<T> on the heap, wrapping the given value and initializing strong/weak atomic counters.

use std::sync::Arc;
let shared_data = Arc::new(String::from("system_state"));

Arc::clone(this: &Arc<T>) -> Arc<T>

Increments the atomic strong reference count of the Arc pointer. Returns a thread-safe clone pointing to the same heap allocation. This uses CPU atomic operations and is lock-free.

use std::sync::Arc;
let data = Arc::new(42);
let cloned = Arc::clone(&data); // Safe to send to another thread

Quick Reference Guide

use std::sync::Arc;
let a = Arc::new(100);