Question

I am designing my own message bus in C++, which will serve as the back-end for a component based game. The message bus will have the following characteristics:

  • Frequently iterated through, starting at the first element and ending at the last.
  • Infrequent removal of elements at random locations
  • Theoretically limitless number of elements
  • Theoretically limitless number of message types
  • Needs to run as fast as possible
  • All elements will contain a pointer to the message handler
  • Thread safe

My question is:

What is the best container to store such information? This is not limited to standard C++, so boost containers are applicable so long as the container is cross platform between Windows and Linux.

Was it helpful?

Solution 2

A Message Bus is a complex thing and doesn't barely boil down to the representation of a message queue for a single component that is connected to the bus.
As mentioned in a comment, std::queue<MessageType,std::list<MessageType> > should fulfill your primary use cases besides thread safety, but theres a lot more things to consider.

Here's a sample for a thread safe queue implementation: EventQueue.h from STTCL. If you place in std::queue<__T__,std::list<__T__> > as value of STTCL_DEFAULT_DEQUEIMPL(__T__) it should fit your needs, including the find() operation for a particular item.

Depending on your application's use cases you'll need to choose from various messaging patterns for distribution and subscription for certain types of messages.
When I was about to deal with these topics, I found the EAI catalog of messaging patterns extremely useful.

Besides this: Always (ALWAYS!!! Yes! Three exclamation marks) depart message payload from transport!!

A notable transport system for messaging patterns is 0MQ, which provides bindings for various languages. But others are available for C++ implementations (including raw socket based implementations or s.th. like boost::asio).

As for the design of message payload, I found Google Protocol Buffers most useful, portable and flexible for all my requirements in distributed systems (including embedded!).

OTHER TIPS

std::list

  • O(1) Iteration
  • O(1) Removal (Assuming you have an iterator)
  • O(1) Insertion

The main disadvantage of lists is that they lack random access, which is however irrelevant for message queues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top