Non-static, Non-Send Tokio Spawn Blocking with &self and Scoped Threads

⚓ Rust    📅 2026-06-19    👤 surdeus    👁️ 2      

surdeus

I have a function like this:

pub async fn work_async(&self) -> Result<(), Error> {

}

I also have a synchronous implementation of this that uses std::thread::scope to spawn threads in a way where I don't have to deal with 'static lifetimes or Send:

pub fn work_threaded(&self) -> Result<(), Error> {
    std::thread::scope(|s| {
        let a = s.spawn(|| self.work_task_a());
        let b = s.spawn(|| self.work_task_b());

        let _a = a.join().unwrap();
        let _b = b.join().unwrap();

        Ok(())
   }).unwrap()
}

My constraints here are:

  1. I cannot make self Send or 'static.
  2. My work tasks are black boxes, they cannot be made into async functions.
  3. My work tasks absolutely block the calling thread
  4. The work done by both tasks should proceed concurrently and not serially, as each of these operations take around 10 seconds to complete and I can't wait 20 seconds.
  5. I want to not block in my async implementation so that other work on the executors can continue.
  6. My work tasks absolutely need &self, but I could make them &mut self if need be.

I'm trying to look into tokio-scoped but I'm still having trouble with lifetimes.

So I essentially have a future which must live as long as &self but which must be able to spawn (scoped probably) threads.

Is there a way for me to use Pin to somehow get around the lifetime issues? I essentially need to go from a future to tokio::task::spawn_blocking into std::thread::scope and express that this future has the same lifetime as &self so as to ensure everything lives long enough without going to 'static or having to make things Send.

Is this at all possible?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed