1

I'm building a Rust library that exposes the following simple flow to a C++ client application:

  1. Client Application (CA) calls an API to create a FooClient, which amongst other things creates a tokio::Runtime.
  2. CA calls FooClient.lookup("http://stackoverflow.com", callback) where callback is a Function Pointer.
  3. FooClient takes the URI and copies it to a Context struct. The context struct has a reference to the FooClient's tokio::Runtime, amongst other things. This context is passed through several functions of business logic. The Context has an explicit lifetime of 'a, so it is shorter than 'static.
  4. When the heavy processing is done, Rust calls the callback it was given (this was translated to a FnOnce and works fine)

During Step 3's business logic, it is often necessary to make a web request, which I'd like to schedule asynchrounously using the &tokio::Runtime stored in the Context.

Here is simplified code, which does not compile:

fn fork_task(context: &Context, uri: Uri, callback: FnOnce) {
   let handle = context.async_scheduler.handle().clone();
   let th = thread::spawn(move || {
       handle.block_on(async {
           call_service(context, uri);
       });
   });

   th.join().unwrap();
   callback();
}

The error this gives me is:

error[E0621]: explicit lifetime required in the type of `context`
    |
335 |     context: &Context,
    |              -------- help: add explicit lifetime `'static` to the type of `context`: `&Context<'static>`
...
348 |     let th = thread::spawn(move || {
    |              ^^^^^^^^^^^^^ lifetime `'static` required

It actually throws this error for every parameter used within the spawn, not just context. However, I don't think 'static is right here. I think if anything, it should be 'a, which is tied to the explicit lifetime of my Context.

Is there some form of workaround I can do? Perhaps with Arc<Mutex<Context>>, although that doesn't seem like it would do what I want correctly either.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
ZachChilders
  • 415
  • 3
  • 15
  • 1
    Maybe this can help https://docs.rs/crossbeam/0.3.0/crossbeam/struct.Scope.html#method.spawn – max630 May 29 '20 at 04:31
  • 1
    Does this answer your question? [How can I pass a reference to a stack variable to a thread?](https://stackoverflow.com/questions/32750829/how-can-i-pass-a-reference-to-a-stack-variable-to-a-thread) – trent May 29 '20 at 16:01

0 Answers0