[−][src]Crate ruspiro_singleton
Singleton pattern implementation
Provide a cross core synchronisation safe singleton implementation pattern. The Singleton
is intended to be used
to declare crate level static variables that require safe access accross cores. This is helpful where the data
structure used within the Singleton
represents a peripheral where the crate shall only hand out a single instance
to safely represent to unique existance of the peripheral.
HINT
Safe lazy initialization is ensured using atomics. On the Raspberry Pi atmomic operations require the MMU to be configured and active. Otherwise the executing CPU core will hang when trying to execute the atomic operation.
Example
// define the static variable with an inizialization closure static FOO:Singleton<u32> = Singleton::new(20); // define the static variable with an inizialization closure static DEMO:Singleton<Box<Demo>> = Singleton::lazy(&|| { Box::new( Demo::new() ) }); // define the type to be accessible as singleton struct Demo { pub count: u32, } // implement the type that should provided as singlton impl Demo { pub const fn new() -> Self { Demo { count: 0, } } } fn main() { // safely use the singleton inside the closure passed to [with_mut] to update it's contents DEMO.with_mut(|d| { d.count += 10; }); // safely use the singleton inside the closure passed to [with_ref] if read-only access is required DEMO.with_mut(|d| { println!("Value: {}", d.count); }); // you may also return a value from the singleton to work with it after the safe singleton access let val = DEMO.with_ref(|d| { if d.count != 0 { true } else { false } }); }
Structs
Singleton | The Singleton wrapper stores any type |