Last active
August 29, 2015 14:04
-
-
Save film42/0cef2472e6ac75dee2a7 to your computer and use it in GitHub Desktop.
Pub/Sub Broker in C++ but it's not threaded
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <map> | |
namespace postal { | |
template< class T > | |
class broker { | |
public: | |
typedef std::vector< std::function< void ( T ) > > FuncVector; | |
broker() {} | |
void subscribe( std::string channel, std::function< void ( T )> func ) { | |
if( _exists( channel ) ) { | |
m_channels[ channel ].push_back( func ); | |
} else { | |
FuncVector func_vec = { func }; | |
auto pair = std::make_pair( channel , func_vec ); | |
m_channels.insert( pair ); | |
} | |
} | |
void publish( std::vector< std::string > channels, T message ) { | |
for( auto chan : channels ) { | |
publish( chan, message ); | |
} | |
} | |
void publish( std::string channel, T message ) { | |
if( _exists( channel ) ) { | |
for( auto& func : m_channels[ channel ] ) { | |
func( message ); | |
} | |
} | |
} | |
void publish_all( T message ) { | |
for( auto chan : m_channels ) { | |
for( auto func : chan.second ) { | |
func( message ); | |
} | |
} | |
} | |
private: | |
bool _exists( std::string channel ) { | |
return ( m_channels.count( channel ) > 0 ) ? true : false; | |
} | |
std::map< std::string, FuncVector > m_channels; | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "broker.h" | |
// | |
// CHANNELS | |
// | |
#define BLOG_HITS "blog/hits" | |
#define HOME_PAGE_HITS "home/hits" | |
// | |
// TESTER | |
// | |
int main(int argc, const char * argv[]) { | |
postal::broker<int> broker; | |
broker.subscribe( BLOG_HITS, []( int message ) { | |
std::cout << "BLOG: " << message << std::endl; | |
}); | |
broker.publish( HOME_PAGE_HITS, 9999999); | |
broker.subscribe( HOME_PAGE_HITS, []( int message ) { | |
std::cout << "HOME PAGE: " << message << std::endl; | |
}); | |
broker.publish( BLOG_HITS, 34); | |
broker.publish( std::vector< std::string >({ BLOG_HITS, BLOG_HITS, BLOG_HITS }), 55 ); | |
broker.publish_all( 22 ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BLOG: 34 | |
BLOG: 55 | |
BLOG: 55 | |
BLOG: 55 | |
BLOG: 22 | |
HOME PAGE: 22 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment