• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The gRPC Authors
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 
15 #ifndef GRPC_SRC_CORE_LIB_EVENT_ENGINE_POSIX_ENGINE_LOCKFREE_EVENT_H
16 #define GRPC_SRC_CORE_LIB_EVENT_ENGINE_POSIX_ENGINE_LOCKFREE_EVENT_H
17 #include <grpc/support/port_platform.h>
18 
19 #include <atomic>
20 #include <cstdint>
21 
22 #include "absl/status/status.h"
23 #include "src/core/lib/event_engine/posix_engine/posix_engine_closure.h"
24 
25 namespace grpc_event_engine {
26 namespace experimental {
27 
28 class Scheduler;
29 
30 class LockfreeEvent {
31  public:
LockfreeEvent(Scheduler * scheduler)32   explicit LockfreeEvent(Scheduler* scheduler) : scheduler_(scheduler) {}
33 
34   LockfreeEvent(const LockfreeEvent&) = delete;
35   LockfreeEvent& operator=(const LockfreeEvent&) = delete;
36 
37   // These methods are used to initialize and destroy the internal state. These
38   // cannot be done in constructor and destructor because SetReady may be called
39   // when the event is destroyed and put in a freelist.
40   void InitEvent();
41   void DestroyEvent();
42 
43   // Returns true if fd has been shutdown, false otherwise.
IsShutdown()44   bool IsShutdown() const {
45     return (state_.load(std::memory_order_relaxed) & kShutdownBit) != 0;
46   }
47 
48   // Schedules \a closure when the event is received (see SetReady()) or the
49   // shutdown state has been set. Note that the event may have already been
50   // received, in which case the closure would be scheduled immediately.
51   // If the shutdown state has already been set, then \a closure is scheduled
52   // with the shutdown error.
53   void NotifyOn(PosixEngineClosure* closure);
54 
55   // Sets the shutdown state. If a closure had been provided by NotifyOn and has
56   // not yet been scheduled, it will be scheduled with \a shutdown_error.
57   bool SetShutdown(absl::Status shutdown_error);
58 
59   // Signals that the event has been received.
60   void SetReady();
61 
62  private:
63   enum State { kClosureNotReady = 0, kClosureReady = 2, kShutdownBit = 1 };
64 
65   std::atomic<intptr_t> state_;
66   Scheduler* scheduler_;
67 };
68 
69 }  // namespace experimental
70 }  // namespace grpc_event_engine
71 
72 #endif  // GRPC_SRC_CORE_LIB_EVENT_ENGINE_POSIX_ENGINE_LOCKFREE_EVENT_H
73