Module locked

Source
Expand description

§Locked Module - ArcThreadShareLocked

This module provides ArcThreadShareLocked<T>, a safe zero-copy structure for data sharing between threads using read/write locks.

§🚀 Overview

ArcThreadShareLocked<T> is the recommended alternative to ArcThreadShare<T> when you need zero-copy operations with guaranteed thread safety. It provides the performance benefits of zero-copy while maintaining the safety guarantees of lock-based synchronization.

§Key Features

  • Zero-Copy Operations: No data cloning during access
  • Guaranteed Thread Safety: Uses RwLock for safe concurrent access
  • High Performance: Efficient parking_lot synchronization primitives
  • Memory Efficiency: Single copy of data shared across threads
  • No Lost Updates: All operations are guaranteed to succeed
  • Predictable Behavior: Consistent performance under all contention levels

§When to Use ArcThreadShareLocked

§✅ Perfect Use Cases

  • Safe zero-copy operations without the limitations of ArcThreadShare<T>
  • High-frequency updates where ArcThreadShare<T> would lose operations
  • Critical data integrity requirements
  • Predictable performance needs
  • Large data structures where cloning would be expensive
  • Production applications requiring reliability

§🔄 Comparison with Other Patterns

PatternZero-CopyThread SafetyPerformanceReliability
ThreadShareMedium
ArcThreadShare⚠️High (unreliable)
ArcThreadShareLockedHigh

§Example Usage

§Basic Operations

use thread_share::ArcThreadShareLocked;

let counter = ArcThreadShareLocked::new(0);

// Safe zero-copy operations
counter.update(|x| *x += 1);
counter.update(|x| *x += 2);

assert_eq!(counter.get(), 3);

§From ThreadShare

use thread_share::{share, ArcThreadShareLocked};

let data = share!(String::from("Hello"));
let arc_data = data.as_arc_locked();
let locked_share = ArcThreadShareLocked::from_arc(arc_data);

// Safe zero-copy with guaranteed thread safety
locked_share.update(|s| s.push_str(" World"));

§High-Frequency Updates

use thread_share::ArcThreadShareLocked;
use std::thread;

let counter = ArcThreadShareLocked::new(0);
let clone = counter.clone();

// Spawn multiple threads for high-frequency updates
let handles: Vec<_> = (0..10).map(|_| {
    let counter_clone = clone.clone();
    thread::spawn(move || {
        for _ in 0..10000 {
            counter_clone.update(|x| *x += 1);
        }
    })
}).collect();

// Wait for all threads
for handle in handles {
    handle.join().unwrap();
}

// All updates are guaranteed to succeed
assert_eq!(counter.get(), 100000);

§Performance Characteristics

  • Low Contention: Excellent performance, minimal overhead
  • Medium Contention: Good performance with some lock contention
  • High Contention: Consistent performance, no lost operations
  • Memory Usage: Minimal overhead from lock structures
  • Scalability: Scales well with thread count

§Thread Safety

ArcThreadShareLocked<T> automatically implements Send and Sync traits, making it safe to use across thread boundaries. The internal RwLock ensures that all operations are thread-safe and no data races can occur.

§Memory Management

  • Arc: Provides reference counting for shared ownership
  • RwLock: Ensures exclusive write access and concurrent read access
  • No Box Allocation: Unlike ArcThreadShare<T>, no per-operation allocations
  • Efficient Locking: Uses parking_lot for optimal performance

§Best Practices

  1. Use for zero-copy needs: When you need to avoid cloning data
  2. Prefer over ArcThreadShare: For reliable, production applications
  3. Monitor lock contention: Use read() and write() methods appropriately
  4. Keep critical sections short: Minimize time spent holding locks
  5. Use descriptive variable names: Make it clear this is the locked version

§Migration from ArcThreadShare

If you’re currently using ArcThreadShare<T> and experiencing issues:

// Old: Unreliable atomic operations
use thread_share::ArcThreadShare;
let arc_share = ArcThreadShare::new(0);
arc_share.update(|x| *x += 1); // May fail under contention

// New: Reliable locked operations
use thread_share::ArcThreadShareLocked;
let locked_share = ArcThreadShareLocked::new(0);
locked_share.update(|x| *x += 1); // Always succeeds

§Error Handling

Unlike ArcThreadShare<T>, ArcThreadShareLocked<T> operations never fail due to contention. All operations are guaranteed to complete successfully, making error handling much simpler.

§Integration with ThreadShare

ArcThreadShareLocked<T> integrates seamlessly with ThreadShare<T>:

use thread_share::{share, ArcThreadShareLocked};

let data = share!(vec![1, 2, 3]);

// Get locked version for zero-copy operations
let arc_data = data.as_arc_locked();
let locked_share = ArcThreadShareLocked::from_arc(arc_data);

// Use locked version in threads
locked_share.update(|v| v.push(4));

// Changes are visible in original ThreadShare
assert_eq!(data.get(), vec![1, 2, 3, 4]);

Structs§

ArcThreadShareLocked
Helper structure for working with Arc<RwLock> directly (with locks)