1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 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 FFRT_BASE_QUEUE_H 16 #define FFRT_BASE_QUEUE_H 17 18 #include <atomic> 19 #include <chrono> 20 #include <map> 21 #include <mutex> 22 #include <memory> 23 #include "c/queue.h" 24 #include "cpp/condition_variable.h" 25 #include "internal_inc/non_copyable.h" 26 #include "queue_strategy.h" 27 28 namespace ffrt { 29 class QueueTask; 30 class Loop; 31 32 enum QueueAction { 33 INACTIVE = -1, // queue is nullptr or serial queue is empty 34 SUCC, 35 FAILED, 36 CONCURRENT, // concurrency less than max concurrency 37 }; 38 39 class BaseQueue : public NonCopyable { 40 public: 41 BaseQueue(); 42 virtual ~BaseQueue() = default; 43 44 virtual int Push(QueueTask* task) = 0; 45 virtual QueueTask* Pull() = 0; 46 virtual bool GetActiveStatus() = 0; 47 virtual int GetQueueType() const = 0; 48 virtual void Remove(); 49 virtual int Remove(const char* name); 50 virtual int Remove(const QueueTask* task); 51 virtual void Stop(); 52 IsOnLoop()53 virtual bool IsOnLoop() 54 { 55 return false; 56 } 57 GetMapSize()58 inline uint64_t GetMapSize() 59 { 60 std::unique_lock lock(mutex_); 61 return whenMap_.size(); 62 } 63 GetQueueId()64 inline uint32_t GetQueueId() const 65 { 66 return queueId_; 67 } 68 69 virtual bool HasTask(const char* name); 70 71 protected: GetNow()72 inline uint64_t GetNow() const 73 { 74 return std::chrono::duration_cast<std::chrono::microseconds>( 75 std::chrono::steady_clock::now().time_since_epoch()).count(); 76 } 77 78 void Stop(std::multimap<uint64_t, QueueTask*>& whenMap); 79 void Remove(std::multimap<uint64_t, QueueTask*>& whenMap); 80 int Remove(const QueueTask* task, std::multimap<uint64_t, QueueTask*>& whenMap); 81 int Remove(const char* name, std::multimap<uint64_t, QueueTask*>& whenMap); 82 bool HasTask(const char* name, std::multimap<uint64_t, QueueTask*> whenMap); 83 84 const uint32_t queueId_; 85 bool isExit_ { false }; 86 std::atomic_bool isActiveState_ { false }; 87 std::multimap<uint64_t, QueueTask*> whenMap_; 88 QueueStrategy<QueueTask>::DequeFunc dequeFunc_ { nullptr }; 89 90 ffrt::mutex mutex_; 91 ffrt::condition_variable cond_; 92 }; 93 94 std::unique_ptr<BaseQueue> CreateQueue(int queueType, const ffrt_queue_attr_t* attr); 95 } // namespace ffrt 96 97 #endif // FFRT_BASE_QUEUE_H 98