olp-cpp-sdk 1.24.0
Loading...
Searching...
No Matches
SyncQueue.inl
1/*
2 * Copyright (C) 2019 HERE Europe B.V.
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 * SPDX-License-Identifier: Apache-2.0
17 * License-Filename: LICENSE
18 */
19
20#pragma once
21
22namespace olp {
23namespace thread {
24
25template <typename T, typename Container>
26inline SyncQueue<T, Container>::SyncQueue() noexcept : closed_(false) {}
27
28template <typename T, typename Container>
29inline SyncQueue<T, Container>::~SyncQueue() {
30 Close();
31}
32
33template <typename T, typename Container>
34inline bool SyncQueue<T, Container>::Empty() const {
35 std::lock_guard<std::mutex> lock(mutex_);
36 return queue_.empty();
37}
38
39template <typename T, typename Container>
41 {
42 std::lock_guard<std::mutex> lock(mutex_);
43 closed_ = true;
44 queue_ = Container();
45 }
46 ready_.notify_all();
47}
48
49template <typename T, typename Container>
50inline bool SyncQueue<T, Container>::Pull(T& element) {
51 std::unique_lock<std::mutex> lock(mutex_);
52 ready_.wait(lock, [this]() { return !queue_.empty() || closed_; });
53
54 if (closed_) {
55 return false;
56 }
57
58 element = std::move(queue_.front());
59 queue_.pop();
60 return true;
61}
62
63template <typename T, typename Container>
64inline void SyncQueue<T, Container>::Push(T&& element) {
65 {
66 std::lock_guard<std::mutex> lock(mutex_);
67
68 // Do not push on a closed queue
69 if (closed_) {
70 return;
71 }
72
73 queue_.push(std::forward<T>(element));
74 }
75 ready_.notify_one();
76}
77
78template <typename T, typename Container>
79inline void SyncQueue<T, Container>::Push(const T& element) {
80 {
81 std::lock_guard<std::mutex> lock(mutex_);
82
83 // Do not push on a closed queue
84 if (closed_) {
85 return;
86 }
87
88 queue_.push(element);
89 }
90 ready_.notify_one();
91}
92
93} // namespace thread
94} // namespace olp
void Push(T &&element)
Forwards the passed element into the SyncQueue instance.
Definition SyncQueue.inl:64
bool Pull(T &element)
Pulls one element from the SyncQueue instance.
Definition SyncQueue.inl:50
void Close()
Closes this SyncQueue instance, deletes all the queued elements, and blocks you from pulling any elem...
Definition SyncQueue.inl:40
bool Empty() const
Checks whether this SyncQueue instance is empty.
Definition SyncQueue.inl:34
Rules all the other namespaces.
Definition AppleSignInProperties.h:24