Goby3 3.7.0
2026.11.12
Loading...
Searching...
No Matches
subscription_store.h
Go to the documentation of this file.
1// Copyright 2016-2026:
2// GobySoft, LLC (2013-)
3// Community contributors (see AUTHORS file)
4// File authors:
5// Toby Schneider <toby@gobysoft.org>
6//
7//
8// This file is part of the Goby Underwater Autonomy Project Libraries
9// ("The Goby Libraries").
10//
11// The Goby Libraries are free software: you can redistribute them and/or modify
12// them under the terms of the GNU Lesser General Public License as published by
13// the Free Software Foundation, either version 2.1 of the License, or
14// (at your option) any later version.
15//
16// The Goby Libraries are distributed in the hope that they will be useful,
17// but WITHOUT ANY WARRANTY; without even the implied warranty of
18// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19// GNU Lesser General Public License for more details.
20//
21// You should have received a copy of the GNU Lesser General Public License
22// along with Goby. If not, see <http://www.gnu.org/licenses/>.
23
24#ifndef GOBY_MIDDLEWARE_TRANSPORT_DETAIL_SUBSCRIPTION_STORE_H
25#define GOBY_MIDDLEWARE_TRANSPORT_DETAIL_SUBSCRIPTION_STORE_H
26
27#include <condition_variable>
28#include <functional>
29#include <memory>
30#include <mutex>
31#include <set>
32#include <shared_mutex>
33#include <thread>
34#include <typeindex>
35#include <unordered_map>
36#include <vector>
37
39
41
42namespace goby
43{
44namespace middleware
45{
46namespace detail
47{
50{
51 private:
52 // for each thread, stores a map of Datas to SubscriptionStores so that can call poll() on all the stores
53 using StoresMap = std::unordered_map<std::type_index, std::shared_ptr<SubscriptionStoreBase>>;
54 static std::unordered_map<std::thread::id, StoresMap> stores_;
55 static std::shared_timed_mutex stores_mutex_;
56
57 public:
59 virtual ~SubscriptionStoreBase() = default;
60
61 // returns number of data items posted to callbacks
62 static int poll_all(std::thread::id thread_id,
63 std::unique_ptr<std::unique_lock<std::mutex>>& lock)
64 {
65 // make a copy so that other threads can subscribe if
66 // necessary in their callbacks
67 StoresMap stores;
68 {
69 std::shared_lock<std::shared_timed_mutex> stores_lock(stores_mutex_);
70 if (stores_.count(thread_id))
71 stores = stores_.at(thread_id);
72 }
73
74 int poll_items = 0;
75 for (auto const& s : stores) poll_items += s.second->poll(thread_id, lock);
76 return poll_items;
77 }
78
79 static void unsubscribe_all(std::thread::id thread_id)
80 {
81 std::shared_lock<std::shared_timed_mutex> stores_lock(stores_mutex_);
82 if (stores_.count(thread_id))
83 {
84 for (auto const& s : stores_.at(thread_id)) s.second->unsubscribe_all_groups(thread_id);
85 }
86 }
87
88 static void remove(std::thread::id thread_id)
89 {
90 std::lock_guard<decltype(stores_mutex_)> lock(stores_mutex_);
91 stores_.erase(thread_id);
92 }
93
94 protected:
95 template <typename StoreType> static void insert(std::thread::id thread_id)
96 {
97 // check the store, and if there isn't one for this type, create one
98 std::lock_guard<decltype(stores_mutex_)> lock(stores_mutex_);
99
100 if (!stores_.count(thread_id))
101 stores_.insert(std::make_pair(thread_id, StoresMap()));
102
103 auto index = std::type_index(typeid(StoreType));
104 if (!stores_.at(thread_id).count(index))
105 stores_.at(thread_id).insert(
106 std::make_pair(index, std::shared_ptr<StoreType>(new StoreType)));
107 }
108
109 protected:
110 virtual int poll(std::thread::id thread_id,
111 std::unique_ptr<std::unique_lock<std::mutex>>& lock) = 0;
112 virtual void unsubscribe_all_groups(std::thread::id thread_id) = 0;
113};
114
116{
117 DataProtection(std::shared_ptr<std::mutex> dm, std::shared_ptr<std::condition_variable> pcv,
118 std::shared_ptr<std::mutex> pm)
119 : data_mutex(dm), poller_cv(pcv), poller_mutex(pm)
120 {
121 }
122
123 std::shared_ptr<std::mutex> data_mutex;
124 std::shared_ptr<std::condition_variable> poller_cv;
125 std::shared_ptr<std::mutex> poller_mutex;
126};
127
129template <typename Data> class SubscriptionStore : public SubscriptionStoreBase
130{
131 public:
132 static void subscribe(std::function<void(std::shared_ptr<const Data>)> func, const Group& group,
133 std::thread::id thread_id, std::shared_ptr<std::mutex> data_mutex,
134 std::shared_ptr<std::condition_variable> cv,
135 std::shared_ptr<std::mutex> poller_mutex)
136 {
137 {
138 std::lock_guard<std::shared_timed_mutex> lock(subscription_mutex_);
139
140 // insert callback
141 auto it =
142 subscription_callbacks_.insert(std::make_pair(thread_id, Callback(group, func)));
143 // insert group with iterator to callback
144 subscription_groups_.insert(std::make_pair(group, it));
145
146 // if necessary, create a DataQueue for this thread
147 auto queue_it = data_.find(thread_id);
148 if (queue_it == data_.end())
149 {
150 auto bool_it_pair = data_.insert(std::make_pair(thread_id, DataQueue()));
151 queue_it = bool_it_pair.first;
152 }
153 queue_it->second.create(group);
154
155 // if we don't have a condition variable already for this thread, store it
156 if (!data_protection_.count(thread_id))
157 data_protection_.insert(std::make_pair(
158 thread_id, detail::DataProtection(data_mutex, cv, poller_mutex)));
159 }
160
161 // try inserting a copy of this templated class via the base class for SubscriptionStoreBase::poll_all to use
162 SubscriptionStoreBase::insert<SubscriptionStore<Data>>(thread_id);
163 }
164
165 static void unsubscribe(const Group& group, std::thread::id thread_id)
166 {
167 {
168 std::lock_guard<std::shared_timed_mutex> lock(subscription_mutex_);
169
170 // iterate over subscriptions for this group, and erase the ones belonging to this thread_id
171 auto range = subscription_groups_.equal_range(group);
172 for (auto it = range.first; it != range.second;)
173 {
174 auto sub_thread_id = it->second->first;
175
176 if (sub_thread_id == thread_id)
177 {
178 subscription_callbacks_.erase(it->second);
179 it = subscription_groups_.erase(it);
180 }
181 else
182 {
183 ++it;
184 }
185 }
186
187 // remove the dataqueue for this group
188 auto queue_it = data_.find(thread_id);
189 queue_it->second.remove(group);
190 }
191 }
192
193 static void publish(std::shared_ptr<const Data> data, const Group& group,
194 const Publisher<Data>& publisher)
195 {
196 // push new data
197 // build up local vector of relevant condition variables while locked
198 std::vector<detail::DataProtection> cv_to_notify;
199 {
200 std::shared_lock<std::shared_timed_mutex> lock(subscription_mutex_);
201
202 auto range = subscription_groups_.equal_range(group);
203 for (auto it = range.first; it != range.second; ++it)
204 {
205 std::thread::id thread_id = it->second->first;
206
207 // don't store a copy if publisher == subscriber, and echo is false
208 if (thread_id != std::this_thread::get_id() || publisher.cfg().echo())
209 {
210 // protect the DataQueue we are writing to
211 std::unique_lock<std::mutex> lock(*(data_protection_.at(thread_id).data_mutex));
212 auto queue_it = data_.find(thread_id);
213 queue_it->second.insert(group, data);
214 cv_to_notify.push_back(data_protection_.at(thread_id));
215 }
216 }
217 }
218
219 // now that the subscription and data mutexes are released, wake the subscriber threads
220 for (const auto& data_protection : cv_to_notify)
221 notify_poller(*data_protection.poller_mutex, *data_protection.poller_cv);
222 }
223
224 private:
225 int poll(std::thread::id thread_id,
226 std::unique_ptr<std::unique_lock<std::mutex>>& lock) override
227 {
228 std::vector<std::pair<std::shared_ptr<typename Callback::CallbackType>,
229 std::shared_ptr<const Data>>>
230 data_callbacks;
231 int poll_items_count = 0;
232
233 {
234 std::shared_lock<std::shared_timed_mutex> sub_lock(subscription_mutex_);
235
236 auto queue_it = data_.find(thread_id);
237 if (queue_it == data_.end())
238 return 0; // no subscriptions
239
240 std::unique_lock<std::mutex> data_lock(
241 *(data_protection_.find(thread_id)->second.data_mutex));
242
243 // loop over all Groups stored in this DataQueue
244 for (auto data_it = queue_it->second.cbegin(), end = queue_it->second.cend();
245 data_it != end; ++data_it)
246 {
247 const Group& group = data_it->first;
248 auto group_range = subscription_groups_.equal_range(group);
249 // For a given Group, loop over all subscriptions to this Group
250 for (auto group_it = group_range.first; group_it != group_range.second; ++group_it)
251 {
252 if (group_it->second->first != thread_id)
253 continue;
254
255 // store the callback function and datum for all the elements queued
256 for (auto& datum : data_it->second)
257 {
258 ++poll_items_count;
259 // we have data, no need to keep this lock any longer
260 if (lock)
261 lock.reset();
262 data_callbacks.push_back(
263 std::make_pair(group_it->second->second.callback, datum));
264 }
265 }
266 queue_it->second.clear(group);
267 }
268 }
269
270 // now that we're no longer blocking the subscription or data mutex, actually run the callbacks
271 for (const auto& callback_datum_pair : data_callbacks)
272 (*callback_datum_pair.first)(std::move(callback_datum_pair.second));
273
274 return poll_items_count;
275 }
276
277 void unsubscribe_all_groups(std::thread::id thread_id) override
278 {
279 {
280 std::lock_guard<std::shared_timed_mutex> lock(subscription_mutex_);
281
282 for (auto it = subscription_groups_.begin(); it != subscription_groups_.end();)
283 {
284 auto sub_thread_id = it->second->first;
285
286 if (sub_thread_id == thread_id)
287 {
288 subscription_callbacks_.erase(it->second);
289 it = subscription_groups_.erase(it);
290 }
291 else
292 {
293 ++it;
294 }
295 }
296
297 data_.erase(thread_id);
298 data_protection_.erase(thread_id);
299 }
300 }
301
302 private:
303 struct Callback
304 {
305 using CallbackType = std::function<void(std::shared_ptr<const Data>)>;
306 Callback(const Group& g, const std::function<void(std::shared_ptr<const Data>)>& c)
307 : group(g), callback(new CallbackType(c))
308 {
309 }
310 Group group;
311 std::shared_ptr<CallbackType> callback;
312 };
313
314 class DataQueue
315 {
316 private:
317 std::unordered_map<Group, std::vector<std::shared_ptr<const Data>>> data_;
318
319 public:
320 void create(const Group& g)
321 {
322 auto it = data_.find(g);
323 if (it == data_.end())
324 data_.insert(std::make_pair(g, std::vector<std::shared_ptr<const Data>>()));
325 }
326 void remove(const Group& g) { data_.erase(g); }
327
328 void insert(const Group& g, std::shared_ptr<const Data> datum)
329 {
330 data_.find(g)->second.push_back(datum);
331 }
332 void clear(const Group& g) { data_.find(g)->second.clear(); }
333 bool empty() { return data_.empty(); }
334 typename decltype(data_)::const_iterator cbegin() { return data_.begin(); }
335 typename decltype(data_)::const_iterator cend() { return data_.end(); }
336 };
337
338 // subscriptions for a given thread
339 static std::unordered_multimap<std::thread::id, Callback> subscription_callbacks_;
340 // threads that are subscribed to a given group
341 static std::unordered_multimap<Group,
342 typename decltype(subscription_callbacks_)::const_iterator>
343 subscription_groups_;
344 // condition variable to use for data
345 static std::unordered_map<std::thread::id, detail::DataProtection> data_protection_;
346
347 static std::shared_timed_mutex
348 subscription_mutex_; // protects subscription_callbacks, subscription_groups, data_protection, and the overarching data_ map (but not the DataQueues within it, which are protected by the mutexes stored in data_protection_))
349
350 // data for a given thread
351 static std::unordered_map<std::thread::id, DataQueue> data_;
352};
353
354template <typename Data>
355std::unordered_multimap<std::thread::id, typename SubscriptionStore<Data>::Callback>
356 SubscriptionStore<Data>::subscription_callbacks_;
357template <typename Data>
358std::unordered_map<std::thread::id, typename SubscriptionStore<Data>::DataQueue>
359 SubscriptionStore<Data>::data_;
360template <typename Data>
361std::unordered_multimap<goby::middleware::Group,
362 typename decltype(
363 SubscriptionStore<Data>::subscription_callbacks_)::const_iterator>
364 SubscriptionStore<Data>::subscription_groups_;
365template <typename Data>
366std::unordered_map<std::thread::id, detail::DataProtection>
367 SubscriptionStore<Data>::data_protection_;
368
369template <typename Data> std::shared_timed_mutex SubscriptionStore<Data>::subscription_mutex_;
370
371} // namespace detail
372} // namespace middleware
373} // namespace goby
374
375#endif
Class for grouping publications in the Goby middleware. Analogous to "topics" in ROS,...
Definition group.h:60
Class that holds additional metadata and callback functions related to a publication (and is optional...
Definition publisher.h:40
const goby::middleware::protobuf::TransporterConfig & cfg() const
Returns the metadata configuration.
Definition publisher.h:108
Base class for interthread subscription information. Non-template so it can be stored in a single con...
static void remove(std::thread::id thread_id)
virtual int poll(std::thread::id thread_id, std::unique_ptr< std::unique_lock< std::mutex > > &lock)=0
virtual void unsubscribe_all_groups(std::thread::id thread_id)=0
static void insert(std::thread::id thread_id)
static void unsubscribe_all(std::thread::id thread_id)
static int poll_all(std::thread::id thread_id, std::unique_ptr< std::unique_lock< std::mutex > > &lock)
Storage class for a specific interthread subscription (and related data). Used by InterThreadTranspor...
static void subscribe(std::function< void(std::shared_ptr< const Data >)> func, const Group &group, std::thread::id thread_id, std::shared_ptr< std::mutex > data_mutex, std::shared_ptr< std::condition_variable > cv, std::shared_ptr< std::mutex > poller_mutex)
static void unsubscribe(const Group &group, std::thread::id thread_id)
static void publish(std::shared_ptr< const Data > data, const Group &group, const Publisher< Data > &publisher)
goby::util::logger::GroupSetter group(std::string n)
detail namespace with internal helper functions
Definition json.hpp:263
void notify_poller(std::mutex &poll_mutex, std::condition_variable &cv)
Wake a Poller's poll() loop after data has been made available to one of its _poll() implementations.
std::string thread_id(std::thread::id i=std::this_thread::get_id())
Definition common.h:53
The global namespace for the Goby project.
builder< Clock, json_traits > create(Clock c)
Definition jwt.h:4157
STL namespace.
DataProtection(std::shared_ptr< std::mutex > dm, std::shared_ptr< std::condition_variable > pcv, std::shared_ptr< std::mutex > pm)
std::shared_ptr< std::mutex > data_mutex
std::shared_ptr< std::mutex > poller_mutex
std::shared_ptr< std::condition_variable > poller_cv