Module singleton

Module singleton 

Source
Expand description

This file implements a Reentrant Synchronization Singleton, which is used to guard a critical path such that only a single thread may execute it at a time. The general use is:

// Take control of the Singleton. This is a blocking operation.
let lock = common::singleton::Singleton::new();
// ...
if let Some(lock) = lock {
    drop(lock)
}

The primitive is Reentrant, meaning that once a thread owns the object, subsequent calls do not cause recursive deadlock. The intializer will simply return None, and the original MutexGuard acquired by the thread further up the call-stack will remain. This means that if you have multiple critical paths which may overlap, you do not need to worry about causing deadlock–the Singleton will remain owned by the thread for the scope highest in the call-chain:

fn critical_write() {
    // Acquire a lock
    let _lock = common::singleton::Singleton::new();
    println!("Rust already ensures only a single thread can write here, but we're being safe ;)");

    // Because we already have the Singleton in this thread, this instance will be none. The MutexGuard
    // is held by the parent.
    assert!(_lock.is_none())
}

// Acquire a lock for our critical section.
let _lock = common::singleton::Singleton::new();
let x = 1;

// Write. Though we already hold an instance of the Singleton, we can safely call this from this thread.
critical_write();

// The lock will drop here, allowing the entire critical path to execute without multiple acquisitions.

Structs§

Singleton
The Singleton is a Reentrant Synchronization Type that can only be held by a single thread.