request_queue.h (1869B)
1 // Copyright 2022 The Chromium Authors. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CONTENT_ANALYSIS_DEMO_REQUST_QUEUE_H_ 6 #define CONTENT_ANALYSIS_DEMO_REQUST_QUEUE_H_ 7 8 #include <condition_variable> 9 #include <memory> 10 #include <mutex> 11 #include <queue> 12 13 #include "content_analysis/sdk/analysis_agent.h" 14 15 // This class maintains a list of outstanding content analysis requests to 16 // process. Each request is encapsulated in one ContentAnalysisEvent. 17 // Requests are handled in FIFO order. 18 class RequestQueue { 19 public: 20 using Event = content_analysis::sdk::ContentAnalysisEvent; 21 22 RequestQueue() = default; 23 virtual ~RequestQueue() = default; 24 25 // Push a new content analysis event into the queue. 26 void push(std::unique_ptr<Event> event) { 27 std::lock_guard<std::mutex> lock(mutex_); 28 29 events_.push(std::move(event)); 30 31 // Wake before leaving to prevent unpredicatable scheduling. 32 cv_.notify_one(); 33 } 34 35 // Pop the next request from the queue, blocking if necessary until an event 36 // is available. Returns a nullptr if the queue will produce no more 37 // events. 38 std::unique_ptr<Event> pop() { 39 std::unique_lock<std::mutex> lock(mutex_); 40 41 while (!abort_ && events_.size() == 0) 42 cv_.wait(lock); 43 44 std::unique_ptr<Event> event; 45 if (!abort_) { 46 event = std::move(events_.front()); 47 events_.pop(); 48 } 49 50 return event; 51 } 52 53 // Marks the queue as aborted. pop() will now return nullptr. 54 void abort() { 55 std::lock_guard<std::mutex> lg(mutex_); 56 57 abort_ = true; 58 59 // Wake before leaving to prevent unpredicatable scheduling. 60 cv_.notify_all(); 61 } 62 63 private: 64 std::queue<std::unique_ptr<Event>> events_; 65 std::mutex mutex_; 66 std::condition_variable cv_; 67 bool abort_ = false; 68 }; 69 70 #endif // CONTENT_ANALYSIS_DEMO_REQUST_QUEUE_H_