GCC Middle and Back End API Reference
pub-sub.h
Go to the documentation of this file.
1/* Loosely-coupled notifications via the Publish-Subscribe pattern.
2 Copyright (C) 2025 Free Software Foundation, Inc.
3 Contributed by David Malcolm <dmalcolm@redhat.com>.
4
5This file is part of GCC.
6
7GCC is free software; you can redistribute it and/or modify it under
8the terms of the GNU General Public License as published by the Free
9Software Foundation; either version 3, or (at your option) any later
10version.
11
12GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15for more details.
16
17You should have received a copy of the GNU General Public License
18along with GCC; see the file COPYING3. If not see
19<http://www.gnu.org/licenses/>. */
20
21#ifndef GCC_PUB_SUB_H
22#define GCC_PUB_SUB_H
23
24namespace pub_sub {
25
26template <typename Subscriber>
28{
29public:
30 using subscriber = Subscriber;
31
32 // A node within the std::list
33 using subscription = typename std::list<subscriber *>::iterator;
34
35 /* Return this if this channel has subscribers, or nullptr if
36 there are none. */
37 const channel *
39 {
40 if (m_subscribers.empty ())
41 return nullptr;
42 return this;
43 }
44
45 template <typename Message>
46 void publish (const Message &m) const
47 {
48 for (auto sub : m_subscribers)
49 sub->on_message (m);
50 }
51
54 {
55 return m_subscribers.insert (m_subscribers.end (), &s);
56 }
58 {
59 m_subscribers.remove (s);
60 }
61
62private:
63 std::list<subscriber *> m_subscribers;
64};
65
66} // namespace pub_sub
67
68#endif /* GCC_PUB_SUB_H */
Definition pub-sub.h:28
subscription add_subscriber(subscriber &s)
Definition pub-sub.h:53
void unsubscribe(subscription s)
Definition pub-sub.h:57
const channel * get_if_active() const
Definition pub-sub.h:38
void publish(const Message &m) const
Definition pub-sub.h:46
Subscriber subscriber
Definition pub-sub.h:30
typename std::list< subscriber * >::iterator subscription
Definition pub-sub.h:33
std::list< subscriber * > m_subscribers
Definition pub-sub.h:63
Definition pub-sub.h:24