From: Mirek Klimos Date: Tue, 26 Apr 2016 16:58:33 +0000 (-0700) Subject: API to set folly::RequestContext for current scope, try 2 X-Git-Tag: 2016.07.26~321 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=0be0a8cdb26cd0a5c5fdc3006ce67f8c40c1653a;p=folly.git API to set folly::RequestContext for current scope, try 2 Summary: same as D3156698, without changes in Cpp2Connection (which was the only real change in the diff) Reviewed By: haijunz Differential Revision: D3222792 fb-gh-sync-id: 245c7add837c0fc6d0bc84aa7d80b929ba2ce386 fbshipit-source-id: 245c7add837c0fc6d0bc84aa7d80b929ba2ce386 --- diff --git a/folly/io/async/Request.h b/folly/io/async/Request.h index 112f0fa8..5c1b9699 100644 --- a/folly/io/async/Request.h +++ b/folly/io/async/Request.h @@ -111,12 +111,15 @@ class RequestContext { } // The following API is used to pass the context through queues / threads. - // saveContext is called to geta shared_ptr to the context, and + // saveContext is called to get a shared_ptr to the context, and // setContext is used to reset it on the other side of the queue. // + // Whenever possible, use RequestContextScopeGuard instead of setContext + // to make sure that RequestContext is reset to the original value when + // we exit the scope. + // // A shared_ptr is used, because many request may fan out across // multiple threads, or do post-send processing, etc. - static std::shared_ptr setContext(std::shared_ptr ctx) { using std::swap; @@ -135,4 +138,24 @@ class RequestContext { std::map> data_; }; +class RequestContextScopeGuard { + private: + std::shared_ptr prev_; + + public: + // Create a new RequestContext and reset to the original value when + // this goes out of scope. + RequestContextScopeGuard() : prev_(RequestContext::saveContext()) { + RequestContext::create(); + } + + // Set a RequestContext that was previously captured by saveContext(). It will + // be automatically reset to the original value when this goes out of scope. + explicit RequestContextScopeGuard(std::shared_ptr ctx) + : prev_(RequestContext::setContext(std::move(ctx))) {} + + ~RequestContextScopeGuard() { + RequestContext::setContext(std::move(prev_)); + } +}; }