Conquer Space 0.0.0
A space themed grand strategy game set in the near future, with realistic orbital mechanics, and an emphasis on economics and politics.
threadsafequeue.h
Go to the documentation of this file.
1/* Conquer Space
2 * Copyright (C) 2021-2025 Conquer Space
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17#pragma once
18
19#include <mutex>
20#include <queue>
21
22namespace cqsp::engine {
26template <typename T>
28 std::queue<T> queue_;
29 mutable std::mutex mutex_;
30
31 // Moved out of public interface to prevent races between this
32 // and pop().
33 bool empty() const { return queue_.empty(); }
34
35 public:
36 ThreadsafeQueue() = default;
39
41 std::lock_guard<std::mutex> lock(mutex_);
42 queue_ = std::move(other.queue_);
43 }
44
45 virtual ~ThreadsafeQueue() {}
46
47 unsigned long size() const {
48 std::lock_guard<std::mutex> lock(mutex_);
49 return queue_.size();
50 }
51
52 std::optional<T> pop() {
53 std::lock_guard<std::mutex> lock(mutex_);
54 if (queue_.empty()) {
55 return {};
56 }
57 T tmp = queue_.front();
58 queue_.pop();
59 return tmp;
60 }
61
62 void push(const T& item) {
63 std::lock_guard<std::mutex> lock(mutex_);
64 queue_.push(item);
65 }
66};
67} // namespace cqsp::engine
Definition: threadsafequeue.h:27
void push(const T &item)
Definition: threadsafequeue.h:62
ThreadsafeQueue(const ThreadsafeQueue< T > &)=delete
bool empty() const
Definition: threadsafequeue.h:33
std::mutex mutex_
Definition: threadsafequeue.h:29
std::queue< T > queue_
Definition: threadsafequeue.h:28
virtual ~ThreadsafeQueue()
Definition: threadsafequeue.h:45
std::optional< T > pop()
Definition: threadsafequeue.h:52
ThreadsafeQueue(ThreadsafeQueue< T > &&other)
Definition: threadsafequeue.h:40
unsigned long size() const
Definition: threadsafequeue.h:47
ThreadsafeQueue & operator=(const ThreadsafeQueue< T > &)=delete
Definition: application.cpp:55