1 /*
2  * Copyright (c) 2023 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 FOUNDATION_ACE_FRAMEWORKS_BASE_THREAD_SEM_QUEUE_H
17 #define FOUNDATION_ACE_FRAMEWORKS_BASE_THREAD_SEM_QUEUE_H
18 
19 #include <condition_variable>
20 #include <mutex>
21 #include <queue>
22 
23 namespace OHOS::Ace {
24 template<class T>
25 class SemQueue {
26 public:
PopFront(T & t)27     void PopFront(T &t)
28     {
29         std::unique_lock lock(mutex_);
30         if (queue_.empty()) {
31             const auto &func = [this]() {
32                 return !queue_.empty();
33             };
34             cv_.wait(lock, func);
35         }
36         t = queue_.front();
37         queue_.pop();
38     }
39 
Push(const T & t)40     void Push(const T &t)
41     {
42         std::unique_lock lock(mutex_);
43         queue_.push(std::move(t));
44         cv_.notify_all();
45     }
46 
47 private:
48     std::queue<T> queue_;
49     std::mutex mutex_;
50     std::condition_variable cv_;
51 };
52 
53 } // namespace OHOS::Ace
54 #endif // FOUNDATION_ACE_FRAMEWORKS_BASE_THREAD_SEM_QUEUE_H
55