closure_guard.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2014 Baidu, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Authors: Ge,Jun (gejun@baidu.com)
  15. #ifndef BRPC_CLOSURE_GUARD_H
  16. #define BRPC_CLOSURE_GUARD_H
  17. #include <google/protobuf/service.h>
  18. #include "butil/macros.h"
  19. namespace brpc {
  20. // RAII: Call Run() of the closure on destruction.
  21. class ClosureGuard {
  22. public:
  23. ClosureGuard() : _done(NULL) {}
  24. // Constructed with a closure which will be Run() inside dtor.
  25. explicit ClosureGuard(google::protobuf::Closure* done) : _done(done) {}
  26. // Run internal closure if it's not NULL.
  27. ~ClosureGuard() {
  28. if (_done) {
  29. _done->Run();
  30. }
  31. }
  32. // Run internal closure if it's not NULL and set it to `done'.
  33. void reset(google::protobuf::Closure* done) {
  34. if (_done) {
  35. _done->Run();
  36. }
  37. _done = done;
  38. }
  39. // Return and set internal closure to NULL.
  40. google::protobuf::Closure* release() {
  41. google::protobuf::Closure* const prev_done = _done;
  42. _done = NULL;
  43. return prev_done;
  44. }
  45. // True if no closure inside.
  46. bool empty() const { return _done == NULL; }
  47. // Exchange closure with another guard.
  48. void swap(ClosureGuard& other) { std::swap(_done, other._done); }
  49. private:
  50. // Copying this object makes no sense.
  51. DISALLOW_COPY_AND_ASSIGN(ClosureGuard);
  52. google::protobuf::Closure* _done;
  53. };
  54. } // namespace brpc
  55. #endif // BRPC_CLOSURE_GUARD_H