• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 OHOS_APPEXECFWK_CONCURRENT_QUEUE_H
17 #define OHOS_APPEXECFWK_CONCURRENT_QUEUE_H
18 
19 #include <condition_variable>
20 #include <queue>
21 #include <vector>
22 #include "hilog_wrapper.h"
23 
24 namespace OHOS {
25 namespace AppExecFwk {
26 template<typename T>
27 class ConcurrentQueue {
28 public:
ConcurrentQueue()29     ConcurrentQueue() : empty_(){};
30     ~ConcurrentQueue() = default;
31 
32     /**
33      * get data without block
34      * @param task
35      * @return true
36      */
Offer(const T & task)37     bool Offer(const T &task)
38     {
39         std::unique_lock<std::mutex> lock(mutex_);
40         queue_.push_back(task);
41         empty_.notify_all();
42         return true;
43     }
44 
45     /**
46      * get data with block
47      * @param task
48      * @return data
49      */
Take()50     T Take()
51     {
52         std::unique_lock<std::mutex> lock(mutex_);
53         while (queue_.empty()) {
54             HILOG_INFO("ConcurrentQueue::Take blocked");
55             empty_.wait(lock);
56         }
57 
58         T front(queue_.front());
59         queue_.pop_front();
60         return front;
61     }
Poll()62     T Poll()
63     {
64         std::unique_lock<std::mutex> lock(mutex_);
65         if (queue_.empty()) {
66             HILOG_INFO("ConcurrentQueue::Poll empty");
67             return nullptr;
68         }
69         T front(queue_.front());
70         queue_.pop_front();
71         return front;
72     }
73 
Size()74     size_t Size()
75     {
76         return queue_.size();
77     }
Empty()78     size_t Empty()
79     {
80         return queue_.empty();
81     }
Begin()82     auto Begin()
83     {
84         return queue_.begin();
85     }
86 
End()87     auto End()
88     {
89         return queue_.end();
90     }
clear()91     void clear()
92     {
93         std::unique_lock<std::mutex> lock(mutex_);
94         queue_.clear();
95     }
96 
97     ConcurrentQueue(const ConcurrentQueue &) = delete;
98     ConcurrentQueue &operator=(const ConcurrentQueue &) = delete;
99 
100 private:
101     mutable std::mutex mutex_;
102     std::condition_variable empty_;
103     std::deque<T> queue_;
104 };
105 }  // namespace AppExecFwk
106 }  // namespace OHOS
107 
108 #endif
109