public
Created

Asynchronous callbacks..? Kind of?

  • Download Gist
callbackqueue.h
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include <deque>
#include <boost/function.hpp>
 
template <typename ...Args>
class CallbackQueue
{
public:
typedef boost::function< bool (CallbackQueue< Args... >&, Args...) > callback_t;
typedef std::deque< callback_t > callbackList_t;
 
private:
callbackList_t m_callbackList;
typename callbackList_t::iterator m_step;
 
public:
CallbackQueue(callback_t whenDone)
{
m_callbackList.push_back(whenDone);
}
 
void addCallback(callback_t callback)
{
m_callbackList.insert((m_callbackList.end())-1, callback);
}
 
void run(Args... args)
{
m_step = m_callbackList.begin();
doNextStep(args...);
}
 
void doNextStep(Args... args)
{
(*m_step++)(*this, args...);
}
};
demo.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
#include <iostream>
#include <boost/bind.hpp>
 
#include "callbackqueue.h"
 
typedef CallbackQueue<int*,int*> myCallbacks_t;
 
// Imagine these are asynchronous, please!
bool cbA(myCallbacks_t q, int* a, int* b) { ++(*a); q.doNextStep(a, b); return true; }
bool cbB(myCallbacks_t q, int* a, int* b) { ++(*b); q.doNextStep(a, b); return true; }
bool whenDone(myCallbacks_t q, int* a, int* b) { std::cout << *a << "," << *b << std::endl; return true; }
 
int main(int argc, char** argv)
{
myCallbacks_t queue(boost::bind(whenDone, _1, _2, _3));
queue.addCallback(boost::bind(cbA, _1, _2, _3));
queue.addCallback(boost::bind(cbB, _1, _2, _3));
 
int a = 0, b = 0;
 
queue.run(&a, &b);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.