my_handle: Detachable Atomic Reference Counting Handle
my_handle provides the smart pointer MyHandle<T>, which is similar to std::sync::Arc<T> but adds explicit detachable semantics.
This allows the cleanup and deallocation of the inner value T to be triggered early by calling dettach(), even before the Arc reference count reaches zero.
💡 Core Concepts
- Safety Access Guarantee: Once a reference to
Tis successfully obtained via theget()method, that reference is guaranteed to be valid until the correspondingunsafe fn put()is called, even ifdettach()is called by another thread during this time. - Early Drop: The
dettach()method immediately marks the inner valueTas "dead." The actual destruction ofT(T'sdrop) is deferred until no threads hold an active reference lock (i.e., thestackcount reaches zero).
🚀 Usage
use Arc;
use MyHandle;
// 1. Create the handle
let handle = attach;
let clone_1 = clone;
let clone_2 = clone;
// 2. Thread A acquires the lock and accesses the data
let guard = clone_1.get.expect;
let ref_t1 = &*guard;
println!;
// 3. Thread B calls detach
// This immediately prevents future get() calls from succeeding
clone_2.dettach;
println!;
// 4. Verify the detached status
assert!;
// 5. Thread A can still safely access the data
// Although T has been marked as detached, ref_t1 remains valid until put() is called
println!;
// If this is the last active reference lock, the inner value (String) is deallocated at this moment.
drop;
Dependencies
Add the following to your Cargo.toml:
[dependencies] my_handle = "0.1" # Please replace with the actual version
⚠️ Safety Warning (Unsafe)
unsafe fn put(&self)
This method is unsafe and requires the caller to adhere to a strict invariant:
put()MUST be called exactly once for every successfulget()call.
- Undercalling: Will cause
Tnever to be freed, leading to memory leaks. - Overcalling: Will lead to reference count errors, potentially causing Double Free or Use After Free.
Sync and Send
The implementation of MyHandle<T> requires T: Sync + Send.
T: Sync: Allows&Tto be accessed across threads.T: Send: Required because theMyHandledrop logic (which freesT) can execute on any thread.