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