Add new methods to tizen_base::SharedQueue
[platform/core/base/bundle.git] / tizen-shared-queue / shared-queue.hpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef TIZEN_SHARED_QUEUE_SHARED_QUEUE_HPP_
18 #define TIZEN_SHARED_QUEUE_SHARED_QUEUE_HPP_
19
20 #include <condition_variable>
21 #include <memory>
22 #include <mutex>
23 #include <queue>
24 #include <thread>
25 #include <utility>
26
27 namespace tizen_base {
28
29 template <class T>
30 class SharedQueue {
31  public:
32   SharedQueue() = default;
33   virtual ~SharedQueue() = default;
34
35   void Push(T item) {
36     std::lock_guard<std::mutex> lock(mutex_);
37     queue_.push(item);
38     cond_var_.notify_one();
39   }
40
41   bool TryAndPop(T& item) {
42     std::lock_guard<std::mutex> lock(mutex_);
43     if (queue_.empty())
44       return false;
45
46     item = queue_.front();
47     queue_.pop();
48     return true;
49   }
50
51   T WaitAndPop() {
52     std::unique_lock<std::mutex> lock(mutex_);
53     while (queue_.empty())
54       cond_var_.wait(lock);
55
56     auto item = std::move(queue_.front());
57     queue_.pop();
58     return item;
59   }
60
61   bool WaitAndPopFor(T& item, int timeout) {
62     std::unique_lock<std::mutex> lock(mutex_);
63     if (!queue_.empty()) {
64       item = queue_.front();
65       queue_.pop();
66       return true;
67     }
68
69     std::chrono::milliseconds duration(timeout);
70     if (cond_var_.wait_for(lock, duration) == std::cv_status::timeout)
71       return false;
72
73     item = queue_.front();
74     queue_.pop();
75     return true;
76   }
77
78   bool IsEmpty() const {
79     std::lock_guard<std::mutex> lock(mutex_);
80     return queue_.empty();
81   }
82
83   unsigned int Size() const {
84     std::lock_guard<std::mutex> lock(mutex_);
85     return queue_.size();
86   }
87
88  private:
89   std::queue<T> queue_;
90   mutable std::mutex mutex_;
91   std::condition_variable cond_var_;
92 };
93
94 }  // namespace tizen_base
95
96 #endif  // TIZEN_SHARED_QUEUE_SHARED_QUEUE_HPP_