Debian Codegraph @

Utils/ThreadSafeQueue.h

raw symbols SCIP
1 /*
2 RailControl - Model Railway Control Software
3
4 Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org
5
6 RailControl is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 RailControl is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with RailControl; see the file LICENCE. If not see
18 <http://www.gnu.org/licenses/>.
19 */
20
21 #pragma once
22
23 #include <condition_variable>
24 #include <list>
25 #include <mutex>
26
27 namespace Utils
28 {
29 template<class T>
30 class ThreadSafeQueue
31 {
32 public:
33 inline ThreadSafeQueue()
34 : list(),
35 mutex(),
36 run(true)
37 {
38 }
39
40 inline ~ThreadSafeQueue()
41 {
42 Terminate();
43 }
44
45 inline void EnqueueBack(T t)
46 {
47 std::unique_lock<std::mutex> lock(mutex);
48 list.push_back(t);
49 cv.notify_all();
50 }
51
52 inline void EnqueueFront(T t)
53 {
54 std::unique_lock<std::mutex> lock(mutex);
55 list.push_front(t);
56 cv.notify_all();
57 }
58
59 T Dequeue()
60 {
61 std::unique_lock<std::mutex> lock(mutex);
62 while (list.empty())
63 {
64 if (run == false)
65 {
66 return T();
67 }
68 cv.wait_for(lock, std::chrono::seconds(1));
69 }
70 T val = list.front();
71 list.pop_front();
72 return val;
73 }
74
75 inline bool IsEmpty()
76 {
77 std::unique_lock<std::mutex> lock(mutex);
78 return list.empty();
79 }
80
81 inline void Terminate()
82 {
83 run = false;
84 cv.notify_all();
85 }
86
87 private:
88 std::list<T> list;
89 mutable std::mutex mutex;
90 std::condition_variable cv;
91 volatile bool run;
92 };
93 }