tls: find a generic solution for safely passing objects to worker threads
#9,940 opened on Feb 5, 2020
Repository metrics
- Stars
- (27,997 stars)
- PR merge metrics
- (Avg merge 8d) (378 merged PRs in 30d)
Description
When using TLS Slot::set with a callback, it's sometimes useful to add this the to the callback when creating the per thread state. For example, from a filter config constructor, one may do:
FilterConfig::FilterConfig(ThreadLocal::Instance& thread_local):slot_(thread_local.allocateSlot()) {
slot_->set([this,](
Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectSharedPtr {
return this->makeThreadLocalState();
});
}
This is problematic, as the lifetime of the FilterConfig in the main thread is independent of the lifetime of the callback that runs on the worker threads. And in fact FilterConfig may be destructed by the time the callback is run on the worker threads.
A fix for one such instance, and a discussion on how to solve this was initially done here: https://github.com/envoyproxy/envoy/pull/9884
This issue was created for tracking until a generic solution is achieved. Few notes from the discussion in #9884 :
- use a weak pointer to move the variables used into the thread callback. not calling the callback if failing to lock the weak pointer.
- use linting to make sure that
thisis not passed to Slot::set - figure out an easy\generic way to guarantee that the callback uses a valid object. see one such suggestion here
cc @mattklein123