Skip to content

Instantly share code, notes, and snippets.

@deoxxa
Created November 24, 2011 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deoxxa/1391265 to your computer and use it in GitHub Desktop.
Save deoxxa/1391265 to your computer and use it in GitHub Desktop.
Asynchronous callbacks..? Kind of?
#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...);
}
};
#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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment