1 // Copyright 2023 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 #ifndef GRPC_SRC_CORE_LIB_EVENT_ENGINE_WORK_QUEUE_BASIC_WORK_QUEUE_H 15 #define GRPC_SRC_CORE_LIB_EVENT_ENGINE_WORK_QUEUE_BASIC_WORK_QUEUE_H 16 #include <grpc/support/port_platform.h> 17 18 #include <stddef.h> 19 20 #include <deque> 21 22 #include "absl/base/thread_annotations.h" 23 #include "absl/functional/any_invocable.h" 24 25 #include <grpc/event_engine/event_engine.h> 26 27 #include "src/core/lib/event_engine/work_queue/work_queue.h" 28 #include "src/core/lib/gprpp/sync.h" 29 30 namespace grpc_event_engine { 31 namespace experimental { 32 33 // A basic WorkQueue implementation that guards an std::deque with a Mutex 34 // 35 // Implementation note: q_.back is the most recent. q_.front is the oldest. New 36 // closures are added to the back. 37 class BasicWorkQueue : public WorkQueue { 38 public: 39 BasicWorkQueue() = default; 40 // Returns whether the queue is empty 41 bool Empty() const override ABSL_LOCKS_EXCLUDED(mu_); 42 // Returns the size of the queue. 43 size_t Size() const override ABSL_LOCKS_EXCLUDED(mu_); 44 // Returns the most recent element from the queue, or nullptr if either empty 45 // or the queue is under contention. This is the fastest way to retrieve 46 // elements from the queue. 47 // 48 // This method may return nullptr even if the queue is not empty. 49 EventEngine::Closure* PopMostRecent() override ABSL_LOCKS_EXCLUDED(mu_); 50 // Returns the most recent element from the queue, or nullptr if either empty 51 // or the queue is under contention. 52 // This is expected to be the slower of the two ways to retrieve closures from 53 // the queue. 54 // 55 // This method may return nullptr even if the queue is not empty. 56 EventEngine::Closure* PopOldest() override ABSL_LOCKS_EXCLUDED(mu_); 57 // Adds a closure to the queue. 58 void Add(EventEngine::Closure* closure) override ABSL_LOCKS_EXCLUDED(mu_); 59 // Wraps an AnyInvocable and adds it to the the queue. 60 void Add(absl::AnyInvocable<void()> invocable) override 61 ABSL_LOCKS_EXCLUDED(mu_); 62 63 private: 64 mutable grpc_core::Mutex mu_; 65 std::deque<EventEngine::Closure*> q_ ABSL_GUARDED_BY(mu_); 66 }; 67 68 } // namespace experimental 69 } // namespace grpc_event_engine 70 71 #endif // GRPC_SRC_CORE_LIB_EVENT_ENGINE_WORK_QUEUE_BASIC_WORK_QUEUE_H 72