use std::ops::Deref; use std::sync::mpsc::Sender; use parking_lot::Mutex; use thread_local::ThreadLocal; /// Unbounded standard library sender which is stored per thread to get around /// the lack of sync on the standard library version while still being unbounded /// Note: this locks on the cloneable sender, but its done once per thread, so it /// shouldn't result in too much contention pub struct UnboundedSyncSender { clonable_sender: Mutex>, local_senders: ThreadLocal>, } impl UnboundedSyncSender { pub fn new(sender: Sender) -> Self { Self { clonable_sender: Mutex::new(sender), local_senders: ThreadLocal::new(), } } } impl Deref for UnboundedSyncSender { type Target = Sender; fn deref(&self) -> &Self::Target { self.local_senders .get_or(|| self.clonable_sender.lock().clone()) } }