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
- Creation:
EnhancedThreadShare::new(data)orenhanced_share!(data) - Spawning:
enhanced.spawn(name, function)creates named threads - Execution: Threads run with access to shared data
- Monitoring: Track active threads with
active_threads() - 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§
Sourcepub fn new(data: T) -> Self
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]);Sourcepub fn spawn<F>(&self, name: &str, f: F) -> Result<(), String>
pub fn spawn<F>(&self, name: &str, f: F) -> Result<(), String>
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 receivesThreadShare<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
'staticlifetime - 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");Sourcepub fn spawn_multiple<F>(
&self,
thread_configs: Vec<(&str, F)>,
) -> Result<(), String>
pub fn spawn_multiple<F>( &self, thread_configs: Vec<(&str, F)>, ) -> Result<(), String>
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.
Sourcepub fn spawn_multiple_boxed(
&self,
thread_configs: Vec<(&str, Box<dyn FnOnce(ThreadShare<T>) + Send>)>,
) -> Result<(), String>
pub fn spawn_multiple_boxed( &self, thread_configs: Vec<(&str, Box<dyn FnOnce(ThreadShare<T>) + Send>)>, ) -> Result<(), String>
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");Sourcepub fn join_all(&self) -> Result<(), String>
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);Sourcepub fn active_threads(&self) -> usize
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: 0Sourcepub fn is_complete(&self) -> bool
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 completedSourcepub fn get_threads(&self) -> Arc<Mutex<HashMap<String, JoinHandle<()>>>>
pub fn get_threads(&self) -> Arc<Mutex<HashMap<String, JoinHandle<()>>>>
Gets a reference to the threads HashMap for external management
Sourcepub fn set(&self, new_data: T)
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);pub fn update<F>(&self, f: F)
pub fn read<F, R>(&self, f: F) -> R
pub fn write<F, R>(&self, f: F) -> R
pub fn wait_for_change(&self, timeout: Duration) -> bool
pub fn wait_for_change_forever(&self)
pub fn clone(&self) -> Self
Sourcepub fn to_json(&self) -> Result<String, Error>
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");Sourcepub fn from_json(&self, json_string: &str) -> Result<(), Error>
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);