logical_thread.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. *
  3. * Copyright 2019 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. #include <grpc/support/port_platform.h>
  19. #include <functional>
  20. #include "src/core/lib/debug/trace.h"
  21. #include "src/core/lib/gprpp/atomic.h"
  22. #include "src/core/lib/gprpp/debug_location.h"
  23. #include "src/core/lib/gprpp/mpscq.h"
  24. #include "src/core/lib/gprpp/orphanable.h"
  25. #include "src/core/lib/gprpp/ref_counted.h"
  26. #include "src/core/lib/iomgr/exec_ctx.h"
  27. #ifndef GRPC_CORE_LIB_IOMGR_LOGICAL_THREAD_H
  28. #define GRPC_CORE_LIB_IOMGR_LOGICAL_THREAD_H
  29. namespace grpc_core {
  30. extern DebugOnlyTraceFlag grpc_logical_thread_trace;
  31. class LogicalThreadImpl : public Orphanable {
  32. public:
  33. void Run(std::function<void()> callback,
  34. const grpc_core::DebugLocation& location);
  35. void Orphan() override;
  36. private:
  37. void DrainQueue();
  38. // An initial size of 1 keeps track of whether the logical thread has been
  39. // orphaned.
  40. Atomic<size_t> size_{1};
  41. MultiProducerSingleConsumerQueue queue_;
  42. };
  43. // LogicalThread is a mechanism to schedule callbacks in a synchronized manner.
  44. // All callbacks scheduled on a LogicalThread instance will be executed serially
  45. // in a borrowed thread. The API provides a FIFO guarantee to the execution of
  46. // callbacks scheduled on the thread.
  47. class LogicalThread : public RefCounted<LogicalThread> {
  48. public:
  49. LogicalThread() { impl_ = MakeOrphanable<LogicalThreadImpl>(); }
  50. void Run(std::function<void()> callback,
  51. const grpc_core::DebugLocation& location) {
  52. impl_->Run(callback, location);
  53. }
  54. private:
  55. OrphanablePtr<LogicalThreadImpl> impl_;
  56. };
  57. } /* namespace grpc_core */
  58. #endif /* GRPC_CORE_LIB_IOMGR_LOGICAL_THREAD_H */