1 /*
2  * Copyright (c) 2021 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 QUEUE_POOL_H
17 #define QUEUE_POOL_H
18 
19 #include <atomic>
20 #include <list>
21 #include <memory>
22 #include <mutex>
23 
24 #include "platform/queuepool/queue.h"
25 
26 namespace OHOS {
27 namespace AI {
28 const size_t MAX_QUEUE_LENGTH = 1024U;
29 const size_t MAX_QUEUE_COUNT = 10U;
30 
31 template<class TYPE>
32 class QueuePool {
33     FORBID_COPY_AND_ASSIGN(QueuePool);
34     FORBID_CREATE_BY_SELF(QueuePool);
35 
36     typedef std::list<std::shared_ptr<Queue<TYPE>>> Queues;
37 public:
38     /**
39      * Acquire singleton instance.
40      *
41      * @param [in] singleQueueCapacity Capacity for single queue.
42      * @return A pointer to the singleton instance.
43      */
44     static QueuePool *GetInstance(size_t singleQueueCapacity = MAX_QUEUE_LENGTH);
45 
46     /**
47      * Release the singleton instance.
48      */
49     static void ReleaseInstance();
50 
51     /**
52      * Obtain a queue from the available queue pool.
53      *
54      * @return A shared pointer to the queue obtained.
55      */
56     std::shared_ptr<Queue<TYPE>> Pop();
57 
58     /**
59      * Return the queue to the pool for management.
60      *
61      * @param [in] queue A queue to push back.
62      */
63     void Push(std::shared_ptr<Queue<TYPE>> &queue);
64 
65     /**
66      * Query the number of currently used queues.
67      *
68      * @return The number of currently used queues.
69      */
70     size_t BusyQueueNum() const;
71 
72 private:
73     static std::mutex mutex_;
74     static QueuePool *instance_;
75     static size_t singleQueueCapacity_;
76 
77 private:
78     std::mutex mutex4Inner_;
79     Queues queues_;
80     std::atomic<size_t> busyQueueNum_;
81 };
82 } // namespace AI
83 } // namespace OHOS
84 
85 #include "platform/queuepool/queue_pool.inl"
86 
87 #endif // QUEUE_POOL_H