你怎么能在铁锈里做一个安全的静电单例?
transmute()
forget()
transmute
.
trait Foo {}struct CBox;impl CBox { /// Stores value in a bound C api, forget(value) fn set<T: Foo>(value: T) { // ... } /// Periodically call this and maybe get a callback invoked fn poll(_: Box<Fn<(EventType, Foo), ()> + Send>) { // ... }}impl Drop for CBox { fn drop(&mut self) { // Safely load all saved Foo's here and discard them, preventing memory leaks }}
#[cfg(test)]mod test { struct IsFoo; impl Foo for IsFoo {} impl Drop for IsFoo { fn drop(&mut self) { Static::touch(); } } #[test] fn test_drops_actually_work() { guard = Static::lock(); // Prevent any other use of Static concurrently Static::reset(); // Set to zero { let c = CBox; c.set(IsFoo); c.set(IsFoo); c.poll(/*...*/); } assert!(Static::get() == 2); // Assert that all expected drops were invoked guard.release(); }}
Semaphore
init
:
/// Global instancestatic mut INSTANCE_LOCK: bool = false;static mut INSTANCE: *mut StaticUtils = 0 as *mut StaticUtils;static mut WRITE_LOCK: *mut Semaphore = 0 as *mut Semaphore;static mut LOCK: *mut Semaphore = 0 as *mut Semaphore; /// Generate instances if they don't existunsafe fn init() { if !INSTANCE_LOCK { INSTANCE_LOCK = true; INSTANCE = transmute(box StaticUtils::new()); WRITE_LOCK = transmute(box Semaphore::new(1)); LOCK = transmute(box Semaphore::new(1)); }}
紫衣仙女
尚方宝剑之说
相关分类