Skip to content

Getting Rid of Send Requirement #2

Description

@anlumo

Hello,

Correct me if I'm wrong, but it looks to me like the only reason why the type stored in the Desync has to be Send is that it's passed to its own desync thread in Desync::new. What if there would be an alternative function to construct a Desync using an 'static + Send + FnOnce() -> T that is called on that thread to create the wrapped object?

I currently have the problem that I need to use a type that's neither Send nor Sync from multiple threads. Since I can't use Desync, this is the quick replacement I could come up with:

use std::sync::mpsc;

struct NonSendDesync<T: 'static>(
    Option<(
        mpsc::Sender<Box<dyn 'static + Send + FnOnce(&mut T)>>,
        std::thread::JoinHandle<()>,
    )>,
);

impl<T: 'static> NonSendDesync<T> {
    pub fn new(f: impl 'static + Send + FnOnce() -> T) -> Self {
        let (sender, receiver): (mpsc::Sender<Box<dyn 'static + Send + FnOnce(&mut T)>>, _) = mpsc::channel();
        let join_handle = std::thread::spawn(move || {
            let mut instance = f();
            while let Ok(f) = receiver.recv() {
                f(&mut instance);
            }
        });

        Self(Some((sender, join_handle)))
    }

    pub fn enqueue(&self, f: impl 'static + Send + FnOnce(&mut T)) {
        self.0.as_ref().unwrap().0.send(Box::new(f)).unwrap();
    }
}

impl<T: 'static> Drop for NonSendDesync<T> {
    fn drop(&mut self) {
        if let Some((sender, join_handle)) = self.0.take() {
            drop(sender);
            join_handle.join().unwrap();
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions