I need to be able to call thread pool methods from any thread
This requires that the thread pool data be in a mutual exclusion mechanism, such as Mutex or RwLock ( RefCell not suitable for multi-threaded situations, see the book ). In addition, each thread must contain a link to the thread pool data, since the thread pool stores the threads, which creates a problem. To solve this problem, we can put the thread pool data in Arc and keep Weak referencing it in each thread. Please note that we use weak references to avoid reference loops .
which effectively end up mutating 1 or more threads (the caller and the target).
This requires that the flow data be in a mutual exclusion mechanism. To complete the requirements, note that since the thread pool data is in Mutex , we cannot return stream references (for which you need to save the thread pool data), so we also put the stream data in Arc .
The following is an example implementation using Mutex ( Playground ):
use std::collections::HashMap; use std::sync::{Arc, Weak, Mutex}; type Id = u32; struct ThreadPool { inner: Arc<Mutex<ThreadPoolInner>>, } struct ThreadPoolInner { pool: HashMap<Id, Arc<Mutex<ThreadInner>>>, id_count: Id, } impl ThreadPool { fn new() -> ThreadPool { let inner = ThreadPoolInner { pool: HashMap::new(), id_count: 0, }; ThreadPool { inner: Arc::new(Mutex::new(inner)) } } fn create(&self) -> Thread { let mut inner = self.inner.lock().unwrap(); let thread = Thread { inner: Arc::new(Mutex::new(ThreadInner { id: inner.id_count, pool: Arc::downgrade(&self.inner), })), }; inner.id_count += 1; let id = inner.id_count; inner.pool.insert(id, thread.inner.clone()); thread } fn get(&self, id: Id) -> Option<Thread> { let inner = self.inner.lock().unwrap(); inner.pool.get(&id).map(|t| Thread { inner: t.clone() }) } fn some_mut_method(&self) { let _inner = self.inner.lock().unwrap(); println!("something with pool"); } } struct Thread { inner: Arc<Mutex<ThreadInner>>, } impl Thread { fn get_pool(&self) -> Option<ThreadPool> { let inner = self.inner.lock().unwrap();
source share