• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 THREAD_SAFE_QUEUE_H
17 #define THREAD_SAFE_QUEUE_H
18 
19 #include <queue>
20 #include <shared_mutex>
21 
22 namespace OHOS {
23 namespace MMI {
24 
25 template <typename T>
26 class ThreadSafeQueue {
27 public:
Push(T elem)28     void Push(T elem)
29     {
30         std::unique_lock<std::shared_mutex> lock(rwMutex_);
31         queue_.push(elem);
32     }
33 
Pop()34     void Pop()
35     {
36         std::unique_lock<std::shared_mutex> lock(rwMutex_);
37         queue_.pop();
38     }
39 
Front()40     T Front()
41     {
42         std::shared_lock<std::shared_mutex> lock(rwMutex_);
43         return queue_.front();
44     }
45 
Back()46     T Back()
47     {
48         std::shared_lock<std::shared_mutex> lock(rwMutex_);
49         return queue_.back();
50     }
51 
Empty()52     bool Empty()
53     {
54         std::shared_lock<std::shared_mutex> lock(rwMutex_);
55         return queue_.empty();
56     }
57 
Size()58     size_t Size()
59     {
60         std::shared_lock<std::shared_mutex> lock(rwMutex_);
61         return queue_.size();
62     }
63 private:
64     std::queue<T> queue_;
65     std::shared_mutex rwMutex_;
66 };
67 } // namespace MMI
68 } // namespace OHOS
69 
70 #endif // THREAD_SAFE_QUEUE_H