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