Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // compile with g++ "pushpull.cpp -o pp -lzmq -lboost_thread"
- #include <stdlib.h>
- #include <iostream>
- #include <boost/format.hpp>
- #include <boost/thread.hpp>
- #include <boost/thread/thread.hpp>
- #include <boost/thread/mutex.hpp>
- #include <zmq.hpp>
- using namespace std;
- using namespace boost;
- class Counter {
- mutex _mutex;
- condition_variable waiting;
- unsigned int count;
- public:
- Counter()
- {
- count = 0;
- }
- void increment()
- {
- mutex::scoped_lock lock(_mutex);
- count ++;
- waiting.notify_all();
- }
- void wait(unsigned int c=0)
- {
- mutex::scoped_lock lock(_mutex);
- if (c==0) {
- c = count + 1;
- }
- while (count < c) {
- waiting.wait(lock);
- }
- }
- };
- void sleeper_thread(zmq::context_t& zmq_ctx,
- Counter& counter,
- barrier& ready_barrier,
- int sleep_time,
- int thread_nr)
- {
- zmq::socket_t puller(zmq_ctx, ZMQ_PULL);
- uint64_t hwm = 1;
- puller.setsockopt(ZMQ_HWM, &hwm, sizeof(hwm));
- string url = (format("inproc://puller.%i") % thread_nr).str();
- puller.bind(url.c_str());
- cout << "bound to "<<url<<endl;
- ready_barrier.wait();
- while(true) {
- sleep(sleep_time);
- zmq::message_t msg;
- puller.recv(&msg);
- cout << "thread "<<thread_nr<<" got message\n";
- counter.increment();
- }
- }
- int main(void)
- {
- zmq::context_t zmq_ctx(1);
- zmq::socket_t pusher(zmq_ctx, ZMQ_PUSH);
- uint64_t hwm = 1;
- pusher.setsockopt(ZMQ_HWM, &hwm, sizeof(hwm));
- barrier ready_barrier(3);
- Counter counter;
- thread fast_worker(sleeper_thread, ref(zmq_ctx),
- ref(counter), ref(ready_barrier),
- 0, 0);
- thread slow_worker(sleeper_thread, ref(zmq_ctx),
- ref(counter), ref(ready_barrier),
- 1, 1);
- ready_barrier.wait();
- pusher.connect("inproc://puller.0");
- pusher.connect("inproc://puller.1");
- for (int i=0; i<20; i++) {
- zmq::message_t msg(0);
- pusher.send(msg);
- }
- counter.wait(20);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment