Inheriting ThreadLocal?


#1

I am building a Lambda function in Rust via crowbar. One thing I would like to be able to do is for each invocation, associate data with the current thread so as to be accessible from method along my chain of calls. A problem I see is that if I use Rayon and the thread_local crate, I imagine that my ThreadLocal instance won’t follow down into child threads. Is there a generally accepted way to work around this?

Specifically, I would like to associate the Lambda request ID supplied by the context as well as a tokio_core::reactor::Core and a rusoto_credential::InstanceMetadataProvider to all execution paths.

If I use Rayon, I imagine that these values will not be copied over into the new child threads. Any ideas?


#2

Any reason not to pass the context around explicitly?


#3

Nothing in particular. I did want my APIs to be as generic as possible, but maybe I should just pass it around in an Arc or something.


#4

My (and I suspect others’ on this forum) suggestion is to make the context explicit and not hide it behind an ambient thread local. There are many advantages to doing that.


#5

Rayon also lets you use non-'static references in most of the API, so you might not even need to wrap it in an Arc. Just let the outer scope own it, and pass your &Context around.