Struct WorkerManager

Source
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

Source

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

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

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 worker
  • handle - 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");
Source

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

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

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

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

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

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

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

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

Source§

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)

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.