I'm building a Rust library that exposes the following simple flow to a C++ client application:
- Client Application (CA) calls an API to create a FooClient, which amongst other things creates a tokio::Runtime.
- CA calls FooClient.lookup("http://stackoverflow.com", callback) where callback is a Function Pointer.
- 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
. - 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.