Struct ArcThreadShareLocked

Source
pub struct ArcThreadShareLocked<T> {
    pub data: Arc<RwLock<T>>,
}
Expand description

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

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

  • 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
  • Production applications requiring reliability

§Example

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);

§Performance

  • 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

Fields§

§data: Arc<RwLock<T>>

Implementations§

Source§

impl<T> ArcThreadShareLocked<T>

Source

pub fn new(data: T) -> Self

Creates a new ArcThreadShareLocked with data

This method creates a new ArcThreadShareLocked<T> instance with the provided data. The data is wrapped in an Arc<RwLock<T>> for thread-safe sharing.

§Arguments
  • data - The initial data to share between threads
§Returns

A new ArcThreadShareLocked<T> instance containing the data.

§Example
use thread_share::ArcThreadShareLocked;

let counter = ArcThreadShareLocked::new(0);
let message = ArcThreadShareLocked::new(String::from("Hello"));
let data = ArcThreadShareLocked::new(vec![1, 2, 3]);
Source

pub fn from_arc(arc: Arc<RwLock<T>>) -> Self

Creates from Arc<RwLock>

This method creates an ArcThreadShareLocked<T> from an existing Arc<RwLock<T>>. Useful when you already have locked data from other sources, such as from ThreadShare<T>::as_arc_locked().

§Arguments
  • arc - An Arc<RwLock<T>> containing the data to share
§Returns

A new ArcThreadShareLocked<T> instance sharing the same data.

§Example
use thread_share::{share, ArcThreadShareLocked};

let data = share!(vec![1, 2, 3]);
let arc_data = data.as_arc_locked();
let locked_share = ArcThreadShareLocked::from_arc(arc_data);

// Now you can use safe zero-copy operations
locked_share.update(|v| v.push(4));
Source

pub fn get(&self) -> T
where T: Clone,

Gets a copy of data

This method retrieves a copy of the current data. The operation is safe but involves cloning the data.

§Requirements

The type T must implement Clone trait.

§Returns

A copy of the current data.

§Example
use thread_share::ArcThreadShareLocked;

let counter = ArcThreadShareLocked::new(42);
let value = counter.get();
assert_eq!(value, 42);
Source

pub fn get_ref(&self) -> RwLockReadGuard<'_, T>

Gets a reference to data (no cloning!)

This method provides read-only access to the data without cloning. The returned guard holds the read lock until it’s dropped.

§Returns

A read guard that provides access to the data.

§Example
use thread_share::ArcThreadShareLocked;

let data = ArcThreadShareLocked::new(vec![1, 2, 3]);

// Get reference without cloning
{
    let guard = data.get_ref();
    assert_eq!(guard.len(), 3);
    assert_eq!(guard[0], 1);
    // Guard is automatically dropped here, releasing the lock
}
§Note

This method will block until the read lock can be acquired. Multiple threads can read simultaneously. For non-blocking behavior, use try_get_ref().

Source

pub fn try_get_ref(&self) -> Option<RwLockReadGuard<'_, T>>

Tries to get a reference to data without blocking

This method attempts to acquire a read lock without blocking. Returns None if the lock cannot be acquired immediately.

§Returns

Some(guard) if the lock was acquired, None if it couldn’t be acquired.

§Example
use thread_share::ArcThreadShareLocked;

let data = ArcThreadShareLocked::new(vec![1, 2, 3]);

// Try to get reference without blocking
if let Some(guard) = data.try_get_ref() {
    assert_eq!(guard.len(), 3);
    assert_eq!(guard[0], 1);
    // Guard is automatically dropped here
} else {
    // Lock was not available
}

// Ensure data is still accessible
assert_eq!(data.get(), vec![1, 2, 3]);
Source

pub fn get_mut(&self) -> RwLockWriteGuard<'_, T>

Gets a mutable reference to data (no cloning!)

This method provides mutable access to the data without cloning. The returned guard holds the write lock until it’s dropped.

§Returns

A write guard that provides mutable access to the data.

§Example
use thread_share::ArcThreadShareLocked;

let data = ArcThreadShareLocked::new(vec![1, 2, 3]);

// Get mutable reference without cloning
{
    let mut guard = data.get_mut();
    guard.push(4);
    // Guard is automatically dropped here, releasing the lock
}

assert_eq!(data.get(), vec![1, 2, 3, 4]);
§Warning

This method will block until the write lock can be acquired. In high-contention scenarios, this can cause delays. For non-blocking behavior, use try_get_mut().

§Best Practices
  • Keep critical sections short to minimize lock contention
  • Always drop the guard explicitly in complex scenarios
  • Consider using try_get_mut() for non-blocking operations
Source

pub fn try_get_mut(&self) -> Option<RwLockWriteGuard<'_, T>>

Tries to get a mutable reference to data without blocking

This method attempts to acquire a write lock without blocking. Returns None if the lock cannot be acquired immediately.

§Returns

Some(guard) if the lock was acquired, None if it couldn’t be acquired.

§Example
use thread_share::ArcThreadShareLocked;

let data = ArcThreadShareLocked::new(vec![1, 2, 3]);

// Try to get mutable reference without blocking
if let Some(mut guard) = data.try_get_mut() {
    guard.push(4);
    // Guard is automatically dropped here
}

// Ensure data is still accessible
assert_eq!(data.get(), vec![1, 2, 3, 4]);
Source

pub fn set(&self, new_data: T)

Sets data

This method replaces the current data with new data.

§Arguments
  • new_data - The new data to set
§Example
use thread_share::ArcThreadShareLocked;

let counter = ArcThreadShareLocked::new(0);
counter.set(100);
assert_eq!(counter.get(), 100);
Source

pub fn update<F>(&self, f: F)
where F: FnOnce(&mut T),

Updates data using a function

This method allows you to modify the data through a closure. The operation is guaranteed to succeed and is thread-safe.

§Arguments
  • f - Closure that receives a mutable reference to the data
§Example
use thread_share::ArcThreadShareLocked;

let counter = ArcThreadShareLocked::new(0);

counter.update(|x| *x += 1);
assert_eq!(counter.get(), 1);

counter.update(|x| *x *= 2);
assert_eq!(counter.get(), 2);
Source

pub fn read<F, R>(&self, f: F) -> R
where F: FnOnce(&T) -> R,

Reads data through a function

This method provides read-only access to the data through a closure. Multiple threads can read simultaneously.

§Arguments
  • f - Closure that receives a reference to the data
§Returns

The result of the closure execution.

§Example
use thread_share::ArcThreadShareLocked;

let data = ArcThreadShareLocked::new(vec![1, 2, 3]);

let length = data.read(|v| v.len());
assert_eq!(length, 3);

let sum: i32 = data.read(|v| v.iter().sum());
assert_eq!(sum, 6);
Source

pub fn write<F, R>(&self, f: F) -> R
where F: FnOnce(&mut T) -> R,

Writes data through a function

This method provides mutable access to the data through a closure. Only one thread can write at a time.

§Arguments
  • f - Closure that receives a mutable reference to the data
§Returns

The result of the closure execution.

§Example
use thread_share::ArcThreadShareLocked;

let data = ArcThreadShareLocked::new(vec![1, 2, 3]);

let length = data.write(|v| {
    v.push(4);
    v.len()
});

assert_eq!(length, 4);
assert_eq!(data.get(), vec![1, 2, 3, 4]);
Source

pub fn to_json(&self) -> Result<String, Error>
where T: Serialize + Clone,

Source

pub fn from_json<D: DeserializeOwned>(&self, json: &str) -> Result<D, Error>

Trait Implementations§

Source§

impl<T> Clone for ArcThreadShareLocked<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Send for ArcThreadShareLocked<T>

Source§

impl<T> Sync for ArcThreadShareLocked<T>

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.