It's been a while since I posted some new content on here. This is mostly
because I've been quite busy trying to be an academic at Purdue. This blog will
get an update soon with a few publications!
Anyways, I've been working a LOT with C++ recently, side-by-side with (and
guided by) my labmates
Tomo
and
Stephen
. (Expect a post about the perfect emacs
setup for C++ development soon, but here's a hint: it involves the usual
suspects
rtags
and
ycmd
) As part of our project, I am currently surveying a few
methods for inter-thread and inter-process communication, which seems to be
what
ZeroMQ
was created for.
After reading through a few chapters of the intro, I managed to piece together
a very basic inter-thread pub-sub example, which simply publishes a few
messages on one thread and consumes them on another. ZeroMQ seems like it's
pretty powerful software and I hope that I get to play with it as part of our
project a little more.
Here's what I came up with, compile as follows: (I do
-O0
and
-g
of course
only when learning a new library)
c++ -c -Wall -O0 -g -fPIC -std=gnu++14 -o zmq_test zmq_test.cc
int main(int argc, char *argv[]) {
zmq::context_t context(0);
zmq::socket_t publisher(context, ZMQ_PUB);
std::string transport("inproc://mytransport");
publisher.bind(transport);
zmq::socket_t subscriber(context, ZMQ_SUB);
subscriber.connect(transport);
subscriber.setsockopt(ZMQ_SUBSCRIBE, "", 0);
size_t nmsg = 10;
size_t nrx = 0;
std::vector<zmq::pollitem_t> p = {{subscriber, 0, ZMQ_POLLIN, 0}};
std::thread subs_thread([&subscriber, &p, &nrx, &nmsg]() {
while (true) {
zmq::message_t rx_msg;
zmq::poll(p.data(), 1, -1);
if (p[0].revents & ZMQ_POLLIN) {
subscriber.recv(&rx_msg);
std::string rx_str;
rx_str.assign(static_cast<char *>(rx_msg.data()), rx_msg.size());
std::cout << "Received: " << rx_str << std::endl;
if (++nrx == nmsg)
break;
for (size_t i = 0; i < nmsg; ++i) {
std::stringstream s;
s << "Hello " << i;
auto msg = s.str();
zmq::message_t message(msg.length());
memcpy(message.data(), msg.c_str(), msg.length());
publisher.send(message);
subs_thread.join();
return 0;