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     unsigned int GetLength() const;
27     unsigned int GetCapacity() const;
28 
29     /**
30     * @brief 初始化队列。
31     * @param capacity 队列容量。
32     * @retval 成功返回0,失败返回-1。
33     */
34     int Init(unsigned int 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 qos        全局队列qos等级。
54     * @param func       元素入队操作。
55     * @retval 返回被推入队列尾部的元素数量。
56     */
57     using PushFunc = void(*)(void*, int);
58     unsigned int PopHeadToAnotherQueue(SpmcQueue& dstQueue, unsigned int elementNum, int qos, PushFunc func);
59 
60 private:
61     void** buf_ = nullptr;
62     unsigned int capacity_ = 0;
63     std::atomic<unsigned int> head_ {0};
64     std::atomic<unsigned int> tail_ {0};
65 };
66 }
67 #endif