Struct EnhancedThreadShare

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

Enhanced ThreadShare with built-in thread management

EnhancedThreadShare<T> extends ThreadShare<T> with automatic thread management capabilities, eliminating the need for manual thread spawning and joining.

§Key Features

  • Automatic Thread Spawning: Spawn threads with a single method call
  • Built-in Thread Tracking: Monitor active thread count and status
  • Automatic Thread Joining: Wait for all threads to complete with join_all()
  • Thread Naming: Give meaningful names to threads for debugging
  • All ThreadShare Features: Inherits all capabilities from ThreadShare<T>

§Example

use thread_share::{enhanced_share, spawn_workers};

let data = enhanced_share!(vec![1, 2, 3]);

// Spawn individual threads
data.spawn("sorter", |data| {
    data.update(|v| v.sort());
});

data.spawn("validator", |data| {
    assert!(data.get().is_sorted());
});

// Wait for completion
data.join_all().expect("Failed to join");

§Thread Lifecycle

  1. Creation: EnhancedThreadShare::new(data) or enhanced_share!(data)
  2. Spawning: enhanced.spawn(name, function) creates named threads
  3. Execution: Threads run with access to shared data
  4. Monitoring: Track active threads with active_threads()
  5. Completion: Wait for all threads with join_all()

§Performance

  • Thread Spawning: Minimal overhead over standard thread::spawn
  • Thread Tracking: Constant-time operations for thread management
  • Memory Usage: Small overhead for thread tracking structures
  • Scalability: Efficient for up to hundreds of threads

Implementations§

Source§

impl<T> EnhancedThreadShare<T>

Source

pub fn new(data: T) -> Self

Creates a new EnhancedThreadShare

This method creates a new EnhancedThreadShare<T> instance with the provided data. The data is wrapped in a ThreadShare<T> for safe sharing between threads.

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

A new EnhancedThreadShare<T> instance.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(0);
let enhanced = EnhancedThreadShare::new(String::from("Hello"));
let enhanced = EnhancedThreadShare::new(vec![1, 2, 3]);
Source

pub fn spawn<F>(&self, name: &str, f: F) -> Result<(), String>
where F: FnOnce(ThreadShare<T>) + Send + 'static, T: Send + Sync + 'static,

Spawns a thread with access to this shared data

This method creates a new thread with the given name and function. The thread receives a clone of the shared data and can safely modify it.

§Arguments
  • name - A descriptive name for the thread (useful for debugging)
  • f - A function that receives ThreadShare<T> and performs the thread’s work
§Requirements

The function F must:

  • Implement FnOnce(ThreadShare<T>) - called once with shared data
  • Implement Send - safe to send across thread boundaries
  • Have 'static lifetime - no borrowed references

The type T must implement Send + Sync + 'static.

§Returns

Ok(()) on success, Err(String) if thread spawning fails.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(0);

// Spawn a worker thread
enhanced.spawn("worker", |data| {
    for _ in 0..100 {
        data.update(|x| *x += 1);
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
}).expect("Failed to spawn worker");

// Spawn a monitor thread
enhanced.spawn("monitor", |data| {
    for _ in 0..10 {
        std::thread::sleep(std::time::Duration::from_millis(100));
        println!("Current value: {}", data.get());
    }
}).expect("Failed to spawn monitor");
Source

pub fn spawn_multiple<F>( &self, thread_configs: Vec<(&str, F)>, ) -> Result<(), String>
where F: FnOnce(ThreadShare<T>) + Send + Clone + 'static, T: Send + Sync + 'static,

Spawns multiple threads with different names and functions

This method spawns multiple threads from a vector of configurations. Each configuration contains a thread name and a function.

§Arguments
  • thread_configs - Vector of (name, function) tuples
§Requirements

The function F must implement Clone in addition to the standard requirements.

§Returns

Ok(()) on success, Err(String) if any thread spawning fails.

Source

pub fn spawn_multiple_boxed( &self, thread_configs: Vec<(&str, Box<dyn FnOnce(ThreadShare<T>) + Send>)>, ) -> Result<(), String>
where T: Send + Sync + 'static,

Spawns multiple threads with boxed closures

This method spawns multiple threads using boxed closures, which allows for different function types in the same vector.

§Arguments
  • thread_configs - Vector of (name, boxed_function) tuples
§Returns

Ok(()) on success, Err(String) if any thread spawning fails.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(0);

let configs = vec![
    ("worker1", Box::new(|data: thread_share::ThreadShare<i32>| { data.update(|x| *x = *x + 1); }) as Box<dyn FnOnce(thread_share::ThreadShare<i32>) + Send>),
    ("worker2", Box::new(|data: thread_share::ThreadShare<i32>| { data.update(|x| *x = *x + 2); }) as Box<dyn FnOnce(thread_share::ThreadShare<i32>) + Send>),
];

enhanced.spawn_multiple_boxed(configs).expect("Failed to spawn threads");
Source

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

Waits for all spawned threads to complete

This method blocks until all spawned threads have finished execution. It joins each thread and returns an error if any thread panics.

§Returns

Ok(()) when all threads complete successfully, Err(String) if any thread fails.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(0);

enhanced.spawn("worker", |data| {
    data.update(|x| *x = *x + 100);
}).expect("Failed to spawn worker");

// Wait for all threads to complete
enhanced.join_all().expect("Thread execution failed");

// Now safe to access the final result
assert_eq!(enhanced.get(), 100);
Source

pub fn active_threads(&self) -> usize

Gets the number of active threads

This method returns the current number of threads that are still running.

§Returns

The number of active threads.

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

let enhanced = EnhancedThreadShare::new(0);

enhanced.spawn("worker", |data| {
    std::thread::sleep(Duration::from_millis(100));
}).expect("Failed to spawn worker");

println!("Active threads: {}", enhanced.active_threads()); // Prints: 1

// Wait for completion
enhanced.join_all().expect("Failed to join");

println!("Active threads: {}", enhanced.active_threads()); // Prints: 0
Source

pub fn is_complete(&self) -> bool

Checks if all threads have completed

This method returns true if there are no active threads, false otherwise.

§Returns

true if all threads have completed, false if any threads are still running.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(0);

enhanced.spawn("worker", |data| {
    data.update(|x| *x = *x + 1);
}).expect("Failed to spawn worker");

assert!(!enhanced.is_complete()); // Thread is still running

enhanced.join_all().expect("Failed to join");

assert!(enhanced.is_complete()); // All threads completed
Source

pub fn get_threads(&self) -> Arc<Mutex<HashMap<String, JoinHandle<()>>>>

Gets a reference to the threads HashMap for external management

Source

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

Delegates all ThreadShare methods

Gets a copy of the shared data.

§Requirements

The type T must implement Clone trait.

§Returns

A copy of the current data.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(42);
let value = enhanced.get();
assert_eq!(value, 42);
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::EnhancedThreadShare;

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

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

Source

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

Source

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

Source

pub fn wait_for_change(&self, timeout: Duration) -> bool

Source

pub fn wait_for_change_forever(&self)

Source

pub fn clone(&self) -> Self

Source§

impl<T: Serialize + Clone + for<'de> Deserialize<'de>> EnhancedThreadShare<T>

Source

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

Serializes the shared data to JSON

This method serializes the current data of type T to a JSON string.

§Returns

A JSON string representation of the data.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(42);
let json_string = enhanced.to_json().expect("Failed to serialize");
assert_eq!(json_string, "42");
Source

pub fn from_json(&self, json_string: &str) -> Result<(), Error>

Deserializes JSON data back into the shared data

This method takes a JSON string and attempts to deserialize it back into the shared data type T.

§Arguments
  • json_string - The JSON string to deserialize
§Returns

Ok(()) on success, Err(serde_json::Error) if deserialization fails.

§Example
use thread_share::EnhancedThreadShare;

let enhanced = EnhancedThreadShare::new(42);
let json_string = enhanced.to_json().unwrap();
enhanced.from_json(&json_string).unwrap();
assert_eq!(enhanced.get(), 42);

Trait Implementations§

Source§

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

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.