pub struct WorkerManager { /* private fields */ }Expand description
Worker Manager for controlling spawned threads
This struct provides methods to control individual workers:
- Pause/resume specific workers
- Remove workers from tracking
- Monitor worker status
- Add new workers programmatically
§Creation
WorkerManager is typically created by the spawn_workers! macro:
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker1: |data| { /* work */ },
worker2: |data| { /* work */ }
});You can also create it directly:
use thread_share::worker_manager::WorkerManager;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
let threads = Arc::new(Mutex::new(HashMap::new()));
let manager = WorkerManager::new_with_threads(threads);Or create an empty manager and add workers later:
use thread_share::worker_manager::WorkerManager;
use std::thread;
// Create empty manager
let manager = WorkerManager::new();
// Add workers as needed
let handle = thread::spawn(|| { /* work */ });
manager.add_worker("worker", handle).expect("Failed to add worker");§Thread Safety
WorkerManager implements Clone and can be safely shared between threads.
All operations are thread-safe and use proper locking mechanisms.
§Example: Complete Worker Lifecycle
use thread_share::{enhanced_share, spawn_workers};
use std::thread;
use std::time::Duration;
let data = enhanced_share!(0u32);
// Start initial workers
let manager = spawn_workers!(data, {
counter: |data| {
for i in 1..=5 {
data.update(|x| *x += i);
thread::sleep(Duration::from_millis(100));
}
}
});
// Add worker programmatically
let data_clone = data.clone();
let handle = thread::spawn(move || {
for _ in 0..3 {
data_clone.update(|x| *x *= 2);
thread::sleep(Duration::from_millis(150));
}
});
manager.add_worker("multiplier", handle).expect("Failed to add worker");
// Monitor workers
println!("Active workers: {}", manager.active_workers());
println!("Worker names: {:?}", manager.get_worker_names());
// Control workers
manager.pause_worker("counter").expect("Failed to pause");
thread::sleep(Duration::from_millis(200));
manager.resume_worker("counter").expect("Failed to resume");
// Wait for completion
manager.join_all().expect("Workers failed");
println!("Final value: {}", data.get());Implementations§
Source§impl WorkerManager
impl WorkerManager
Sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new empty WorkerManager
This method creates a WorkerManager with an empty thread tracking structure. Useful when you want to create a manager first and add workers later.
§Example
use thread_share::worker_manager::WorkerManager;
use std::thread;
// Create empty manager
let manager = WorkerManager::new();
// Add workers programmatically
let handle = thread::spawn(|| {
println!("Worker doing work...");
});
manager.add_worker("worker1", handle).expect("Failed to add worker");
assert_eq!(manager.active_workers(), 1);Sourcepub fn new_with_threads(
threads: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
) -> Self
pub fn new_with_threads( threads: Arc<Mutex<HashMap<String, JoinHandle<()>>>>, ) -> Self
Creates a new WorkerManager with existing thread handles
§Arguments
threads- Arc<Mutex<HashMap<String, JoinHandle<()>>>> containing thread handles
§Example
use thread_share::worker_manager::WorkerManager;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
let threads = Arc::new(Mutex::new(HashMap::new()));
let manager = WorkerManager::new_with_threads(threads);Sourcepub fn add_worker(
&self,
name: &str,
handle: JoinHandle<()>,
) -> Result<(), String>
pub fn add_worker( &self, name: &str, handle: JoinHandle<()>, ) -> Result<(), String>
Adds a new worker to the manager
This method allows you to add workers programmatically after the manager is created. The worker will be tracked and can be managed like any other worker.
§Arguments
name- A descriptive name for the workerhandle- The JoinHandle of the spawned thread
§Returns
Ok(()) on success, Err(String) if a worker with the same name already exists.
§Example
use thread_share::worker_manager::WorkerManager;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::thread;
let threads = Arc::new(Mutex::new(HashMap::new()));
let manager = WorkerManager::new_with_threads(threads.clone());
// Spawn a thread manually
let handle = thread::spawn(|| {
println!("Worker doing work...");
});
// Add it to the manager
manager.add_worker("manual_worker", handle).expect("Failed to add worker");Sourcepub fn pause_worker(&self, name: &str) -> Result<(), String>
pub fn pause_worker(&self, name: &str) -> Result<(), String>
Pauses a specific worker by name
Note: This is a placeholder for future implementation. Currently, Rust doesn’t support pausing threads directly.
§Arguments
name- The name of the worker to pause
§Returns
Ok(()) on success, Err(String) if the worker doesn’t exist
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker: |data| { /* work */ }
});
// Pause the worker
manager.pause_worker("worker").expect("Failed to pause");Sourcepub fn resume_worker(&self, name: &str) -> Result<(), String>
pub fn resume_worker(&self, name: &str) -> Result<(), String>
Resumes a specific worker by name
§Arguments
name- The name of the worker to resume
§Returns
Ok(()) on success, Err(String) if the worker doesn’t exist
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker: |data| { /* work */ }
});
// Pause then resume
manager.pause_worker("worker").expect("Failed to pause");
manager.resume_worker("worker").expect("Failed to resume");Sourcepub fn remove_worker(&self, name: &str) -> Result<(), String>
pub fn remove_worker(&self, name: &str) -> Result<(), String>
Removes a worker from tracking without stopping it
This method removes the worker from the manager’s tracking but doesn’t actually stop the thread. The thread will continue running until it completes naturally.
§Arguments
name- The name of the worker to remove
§Returns
Ok(()) on success, Err(String) if the worker doesn’t exist
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker: |data| { /* work */ }
});
// Remove from tracking
manager.remove_worker("worker").expect("Failed to remove");Sourcepub fn remove_all_workers(&self) -> Result<(), String>
pub fn remove_all_workers(&self) -> Result<(), String>
Removes all workers from tracking without stopping them
This method removes all workers from the manager’s tracking but doesn’t actually stop the threads. The threads will continue running until they complete naturally.
§Returns
Ok(()) on success
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker1: |data| { /* work */ },
worker2: |data| { /* work */ }
});
// Remove all workers from tracking
manager.remove_all_workers().expect("Failed to remove all workers");Sourcepub fn get_worker_names(&self) -> Vec<String>
pub fn get_worker_names(&self) -> Vec<String>
Gets the list of all worker names
§Returns
A Vec<String> containing all worker names
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
counter: |data| { /* work */ },
monitor: |data| { /* work */ }
});
let names = manager.get_worker_names();
assert_eq!(names.len(), 2);
assert!(names.contains(&"counter".to_string()));
assert!(names.contains(&"monitor".to_string()));Sourcepub fn active_workers(&self) -> usize
pub fn active_workers(&self) -> usize
Gets the number of active workers
§Returns
The number of workers currently being tracked
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker1: |data| { /* work */ },
worker2: |data| { /* work */ }
});
assert_eq!(manager.active_workers(), 2);Sourcepub fn is_worker_paused(&self, name: &str) -> bool
pub fn is_worker_paused(&self, name: &str) -> bool
Checks if a specific worker is paused
§Arguments
name- The name of the worker to check
§Returns
true if the worker is paused, false otherwise
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker: |data| { /* work */ }
});
// Initially not paused
assert!(!manager.is_worker_paused("worker"));
// Pause the worker
manager.pause_worker("worker").expect("Failed to pause");
assert!(manager.is_worker_paused("worker"));
// Resume the worker
manager.resume_worker("worker").expect("Failed to resume");
assert!(!manager.is_worker_paused("worker"));Sourcepub fn join_all(&self) -> Result<(), String>
pub fn join_all(&self) -> Result<(), String>
Waits for all workers to complete
This method blocks until all tracked workers have completed. It removes all workers from tracking after they complete.
§Returns
Ok(()) if all workers completed successfully, Err(String) if any worker failed
§Example
use thread_share::{enhanced_share, spawn_workers};
use std::thread;
use std::time::Duration;
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker: |data| {
thread::sleep(Duration::from_millis(100));
data.update(|x| *x += 1);
}
});
// Wait for completion
manager.join_all().expect("Workers failed");
// All workers are now completed and removed
assert_eq!(manager.active_workers(), 0);Trait Implementations§
Source§impl Clone for WorkerManager
impl Clone for WorkerManager
Source§fn clone(&self) -> Self
fn clone(&self) -> Self
Creates a clone of the WorkerManager
The cloned manager shares the same underlying thread tracking data, so operations on one clone will affect the other.
§Example
use thread_share::{enhanced_share, spawn_workers};
let data = enhanced_share!(0u32);
let manager = spawn_workers!(data, {
worker: |data| { /* work */ }
});
// Clone the manager
let manager_clone = manager.clone();
// Both managers track the same workers
assert_eq!(manager.active_workers(), manager_clone.active_workers());1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more