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 16 #ifndef FFRT_SPMC_QUEUE_H 17 #define FFRT_SPMC_QUEUE_H 18 19 #include <atomic> 20 21 namespace ffrt { 22 class SpmcQueue { 23 public: 24 ~SpmcQueue(); 25 26 std::size_t GetLength() const; 27 std::size_t GetCapacity() const; 28 29 /** 30 * @brief 初始化队列。 31 * @param capacity 队列容量。 32 * @retval 成功返回0,失败返回-1。 33 */ 34 int Init(std::size_t capacity); 35 36 /** 37 * @brief 取出队列首部元素。 38 * @retval 指向首部元素的指针,若队列为空则返回nullptr。 39 */ 40 void* PopHead(); 41 42 /** 43 * @brief 将元素推入队列尾部。 44 * @param object 要推入队列的元素。 45 * @retval 成功返回0,失败返回-1。 46 */ 47 int PushTail(void* object); 48 49 /** 50 * @brief 从队列首部批量取出元素后将元素批量推入目标队列尾部。 51 * @param dstQueue 目标队列。 52 * @param elementNum 取出元素数量。 53 * @param func 元素入队操作。 54 * @retval 返回被推入队列尾部的元素数量。 55 */ 56 using PushFunc = void(*)(void*); 57 unsigned int PopHeadToAnotherQueue(SpmcQueue& dstQueue, unsigned int elementNum, PushFunc func); 58 59 private: 60 void** buf_ = nullptr; 61 std::size_t capacity_ = 0; 62 std::atomic<std::size_t> head_ {0}; 63 std::atomic<std::size_t> tail_ {0}; 64 }; 65 } 66 #endif 67