ST_engine  0.3-ALPHA
message_bus.cpp
1 /* This file is part of the "ST" project.
2  * You may use, distribute or modify this code under the terms
3  * of the GNU General Public License version 2.
4  * See LICENCE.txt in the root directory of the project.
5  *
6  * Author: Maxim Atanasov
7  * E-mail: maxim.atanasov@protonmail.com
8  */
9 
10 #include <message_bus.hpp>
11 #include <ST_util/pool_allocator_256.hpp>
12 
13 //message_bus implementation=====================================================
14 
20  std::vector<subscriber *> *temp = &subscribers[arg->msg_name];
21  uint64_t size = temp->size();
22  //Locks aren't really needed here as there won't be any new subscribers in the middle of the game
23  //(if you do want to have subsystems subscribe at random times you should definitely add locks)
24 
25  //TODO: Branch needed? In practice, no messages without subscribers to them will be sent
26  //The branch cannot be removed with an #ifdef though, as the msg_bus is a library.
27  if (size != 0) [[likely]] {
28  temp->operator[](0)->push_message(arg);
29  for (uint64_t i = 1; i < size; ++i) {
30  temp->operator[](i)->push_message(arg->make_copy()); //yes all queues are thread-safe so this is fine
31  }
32  }
33 }
34 
35 static bool singleton_initialized = false;
36 
42  if (singleton_initialized) {
43  throw std::runtime_error("The message bus cannot be initialized more than once!");
44  } else {
45  singleton_initialized = true;
46  }
47 }
48 
55  subscribers.clear();
56  singleton_initialized = false;
57 }
58 
63  subscribers.clear();
64 }
65 
71 void message_bus::subscribe(uint8_t msg, subscriber *sub) {
72  subscribers[msg].emplace_back(sub);
73 }
void clear()
Definition: message_bus.cpp:62
void subscribe(uint8_t msg, subscriber *sub)
Definition: message_bus.cpp:71
void send_msg(message *msg)
Definition: message_bus.cpp:19
A message object passed around in the message bus. Holds anything created with make_data<>().
Definition: message.hpp:21
message * make_copy() const
Definition: message.hpp:87
This class handles a small queue for messages.
Definition: subscriber.hpp:20