This is a simple implementation of publisher/subscriber mechanism for multi-thread program. The code had been written and tested in Ubuntu 16.04 and passed Google's cpplint.
To run the code, please do it as follows
git clone https://github.com/ZhongxingPeng/simple_pubsub.git
cd simple_pubsub
make
./test
The document structure of this code is
├── main.cpp
├── Makefile
├── message.hpp
├── module.cpp
├── module.hpp
├── readme.txt
├── subscriber.cpp
└── subscriber.hpp
The basic idea of this publisher/subscriber mechanism is
- The
main()
function brings up amessage_server
, and passes the handle of themessage_server
to all active threads. - The
message_server
maintains a vector ofTopic
objects. - Each Topic object maintains a vector of pointers to every subscribed threads.
- Any thread or
main()
function can access the subscriber vectors via the handle ofmessage_server
. - To
subscribe/unsubscribe
, justadd/remove
corresponding thread pointerto/from
the subscriber vectors. - To publish a message:
- A thread contact the
message_server
with topic name. Message_server
accesses to the subscriber vector of that topic.- Use that subscriber vector,
message_server
push the message to the message buffer of every subscribed thread. - Every thread moniters its own message buffer in a
for
-loop inrun()
method. - When new message comes, the thread fetch the message from the message buffer, then remeove the message from the buffer.
- A thread contact the
Due to the limited time, several possible improvements remain untouched in this version of the code:
- Consider real-time requirements. For example, in current code, if hard interupt is invoked, the message haven't been fully publish might be lost or demaged.
- Consider lock in parallel threads. For example, in current code, if two messages arrive at the same time, the program might behavior abnormally or crash.
- Code refactoring is needed. In
subscriber.hpp
, cross references are needed to resolved. Because, classMessageServer
uses classSubscriber
, whileSubscribe
also uses classMessageServer
. - Message buffer in every thread might be carefully re-design. Because the buffer might overflow or some message might be lost.