Struct ThreadShare

Source
pub struct ThreadShare<T> { /* private fields */ }
Expand description

Main structure for data exchange between threads

ThreadShare<T> provides comprehensive thread synchronization with automatic change detection and efficient locking mechanisms.

§Features

  • Automatic Cloning: Each thread gets its own clone for safe access
  • Change Detection: Built-in waiting mechanisms for data changes
  • Flexible Access: Read, write, and update operations with proper locking
  • Condition Variables: Efficient waiting for data modifications
  • Thread Safety: Implements Send and Sync automatically

§Example

use thread_share::ThreadShare;
use std::thread;

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

thread::spawn(move || {
    clone.update(|v| v.push(4));
});

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

§Performance

  • Read Operations: Multiple threads can read simultaneously
  • Write Operations: Exclusive access during writes
  • Change Detection: Efficient condition variable notifications
  • Memory Overhead: Minimal overhead from Arc and RwLock structures

Implementations§

Source§

impl<T> ThreadShare<T>

Source

pub fn to_json(&self) -> Result<String, String>

Serializes the current data to JSON string

This method requires the serialize feature to be enabled.

§Returns

JSON string representation of the data, or error string if serialization fails.

§Example
use thread_share::ThreadShare;

#[cfg(feature = "serialize")]
{
    let data = ThreadShare::new(vec![1, 2, 3]);
    let json = data.to_json().expect("Failed to serialize");
    assert_eq!(json, "[1,2,3]");
}
Source

pub fn from_json(&self, json: &str) -> Result<(), String>

Deserializes data from JSON string

This method requires the serialize feature to be enabled.

§Arguments
  • json - JSON string to deserialize
§Returns

Ok(()) on success, Err(String) if deserialization fails.

§Example
use thread_share::ThreadShare;

#[cfg(feature = "serialize")]
{
    let data = ThreadShare::new(vec![0; 0]);
    data.from_json("[1,2,3]").expect("Failed to deserialize");
    assert_eq!(data.get(), vec![1, 2, 3]);
}
Source§

impl<T> ThreadShare<T>

Source

pub fn new(data: T) -> Self

Creates a new ThreadShare instance with data

§Arguments
  • data - The initial data to share between threads
§Example
use thread_share::ThreadShare;

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

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

Gets a copy of data (for types implementing Clone)

§Requirements

The type T must implement Clone trait.

§Returns

A copy of the current data.

§Example
use thread_share::ThreadShare;

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

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

Gets a reference to data for reading

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::ThreadShare;

let data = ThreadShare::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,

Gets a mutable reference to data

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::ThreadShare;

let data = ThreadShare::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 set(&self, new_data: T)

Sets new data and notifies waiting threads

This method replaces the current data and notifies all threads waiting for changes.

§Arguments
  • new_data - The new data to set
§Example
use thread_share::ThreadShare;
use std::thread;

let data = ThreadShare::new(0);
let clone = data.clone();

thread::spawn(move || {
    clone.set(100);
});

data.wait_for_change_forever();
assert_eq!(data.get(), 100);
Source

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

Updates data using a function and notifies waiting threads

This method allows you to modify the data through a closure and automatically notifies waiting threads of the change.

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

let counter = ThreadShare::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 wait_for_change(&self, timeout: Duration) -> bool

Waits for data changes with timeout

This method waits for a change notification with a specified timeout.

§Arguments
  • timeout - Maximum time to wait for changes
§Returns

true if the timeout was reached, false if a change occurred.

§Example
use thread_share::ThreadShare;
use std::time::Duration;

let data = ThreadShare::new(0);
let clone = data.clone();

// Spawn thread that will change data after 200ms
std::thread::spawn(move || {
    std::thread::sleep(Duration::from_millis(200));
    clone.set(100);
});

// Wait for change with 100ms timeout
let timed_out = data.wait_for_change(Duration::from_millis(100));
assert!(timed_out); // Should timeout

// Wait for change with 300ms timeout
let timed_out = data.wait_for_change(Duration::from_millis(300));
assert!(!timed_out); // Should not timeout
Source

pub fn wait_for_change_forever(&self)

Waits for data changes infinitely

This method waits indefinitely for a change notification.

§Example
use thread_share::ThreadShare;
use std::thread;
use std::time::Duration;

let data = ThreadShare::new(0);
let clone = data.clone();

thread::spawn(move || {
    thread::sleep(Duration::from_millis(100));
    clone.set(100);
});

// Wait indefinitely for change
data.wait_for_change_forever();
assert_eq!(data.get(), 100);
Source

pub fn clone(&self) -> Self

Creates a clone for use in another thread

This method creates a new ThreadShare<T> instance that shares the same underlying data. Each clone can be safely moved to different threads.

§Returns

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

§Example
use thread_share::ThreadShare;
use std::thread;
use std::time::Duration;

let data = ThreadShare::new(0);
let clone1 = data.clone();
let clone2 = data.clone();

// Each clone can be used in different threads
thread::spawn(move || {
    clone1.set(100);
});

thread::spawn(move || {
    clone2.set(200);
});

// Main thread waits for changes
data.wait_for_change_forever();
Source

pub fn into_arc(self) -> Arc<RwLock<T>>

Gets Arc on data for transfer to thread without cloning

This method converts the ThreadShare<T> into an Arc<RwLock<T>>, which can be moved into threads without cloning the ThreadShare itself.

§Returns

An Arc<RwLock<T>> containing the shared data.

§Example
use thread_share::ThreadShare;
use std::thread;

let data = ThreadShare::new(0);
let arc_data = data.into_arc();

thread::spawn(move || {
    let mut guard = arc_data.write();
    *guard += 100;
});
Source

pub fn as_arc_locked(&self) -> Arc<RwLock<T>>

Gets Arc<RwLock> for version with locks

This method returns an Arc<RwLock<T>> that shares the same data as this ThreadShare<T>. This is useful when you need to work directly with the underlying Arc<RwLock<T>> structure.

§Returns

An Arc<RwLock<T>> sharing the same data.

§Example
use thread_share::ThreadShare;

let data = ThreadShare::new(vec![1, 2, 3]);
let arc_data = data.as_arc_locked();

// Use the Arc<RwLock<T>> directly
let mut guard = arc_data.write();
guard.push(4);
drop(guard);

// Changes are visible in the original ThreadShare
assert_eq!(data.get(), vec![1, 2, 3, 4]);
Source

pub fn as_arc(&self) -> Arc<AtomicPtr<T>>
where T: Clone,

Gets Arc on data for transfer to thread without cloning (reference)

This method creates an Arc<AtomicPtr<T>> from the current data. Warning: This creates an independent copy of the data, not a shared reference. Changes to the returned Arc<AtomicPtr<T>> will not be visible in the original ThreadShare<T>.

§Requirements

The type T must implement Clone trait.

§Returns

An Arc<AtomicPtr<T>> containing a copy of the current data.

§Warning

This method creates an independent copy of the data. Use as_arc_locked() if you need a shared reference to the same data.

§Example
use thread_share::ThreadShare;

let data = ThreadShare::new(vec![1, 2, 3]);
let arc_data = data.as_arc();

// This modifies the copy, not the original
// Use ArcThreadShare::from_arc(arc_data) to work with it

Trait Implementations§

Source§

impl<T> Clone for ThreadShare<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 ThreadShare<T>

Source§

impl<T> Sync for ThreadShare<T>

Auto Trait Implementations§

§

impl<T> Freeze for ThreadShare<T>

§

impl<T> !RefUnwindSafe for ThreadShare<T>

§

impl<T> Unpin for ThreadShare<T>

§

impl<T> !UnwindSafe for ThreadShare<T>

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.