async/callback.cpp
This is a simple example showing how to send work to some thread and receive the results in a callback.
#include <iostream>
#include <list>
#include <boost/bind.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>
#include <toast/async/worker_pool.hpp>
#include <toast/async/thread_specific_request_queue.hpp>
boost::condition condition;
boost::mutex mutex;
void notify()
{
boost::mutex::scoped_lock lock(mutex);
std::cout << "YooHoo, I've put data on your queue!" << std::endl;
condition.notify_one();
}
int do_work(int i, int j)
{
std::cout << "So... you want to know what " << i << " + " << j
<< " is do ya?" << std::endl;
return i + j;
}
void callback(int i)
{
std::cout << "How would I have ever known that it was " << i
<< " without toast::async?" << std::endl;
}
int main()
{
toast::async::init_default_worker_pool(3, true);
toast::async::thread_specific_request_queue::on_push(¬ify);
toast::async::request r =
toast::async::make_request<int>(boost::bind(&do_work, 5, 12), &callback);
toast::async::default_worker_pool().push(r);
std::list<toast::async::request> current;
boost::mutex::scoped_lock lock(mutex);
while(current.empty()) {
toast::async::thread_specific_request_queue::pop(current);
if(current.empty()) condition.wait(lock);
}
current.front()();
}