#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#define THREAD_POOL_SIZE 10
void TimerCallback(boost::system::error_code ec, std::size_t i, std::size_t retry) {
std::stringstream tmp;
tmp << "Timer(" << ec.value() << ":" << ec.message() << "-" << retry << "-" << i << ")\n";
}
//
// MAIN
//
int _tmain(int argc, _TCHAR* argv[])
{
try
{
boost::asio::io_service io(THREAD_POOL_SIZE);
boost::asio::io_service::work *moreWorkToCome = new boost::asio::io_service::work(io);
// Create a pool of worker threads.
std::vector<boost::shared_ptr<boost::thread> > threads;for (std::size_t i = 0; i < THREAD_POOL_SIZE; ++i)
{
boost::shared_ptr<boost::thread> thread(new boost::thread(
boost::bind(&boost::asio::io_service::run, &io)
));
threads.push_back(thread);
}
// Lets
enqueue more tasks to run after a given time
std::vector<boost::asio::deadline_timer *> timers;
for (std::size_t i = 1; i<50; i++)
{
boost::asio::deadline_timer *timer = new boost::asio::deadline_timer(io);timer->expires_from_now(boost::posix_time::seconds(3));
timer->async_wait(boost::bind(&TimerCallback, boost::asio::placeholders::error, i, 0));
timers.push_back(timer);
}
std::cout << "\nALL TASKS QUEUED\n";
// Now that all tasks have been queued we don't want to hold on any of the worker threads
delete moreWorkToCome;
std::cout << "\nRELEASE THE THREAD POOL\n";
// Wait for all tasks to be processes which also means all threads in the pool will exit.
for (std::size_t i = 0; i < threads.size(); ++i)
threads[i]->join();
// Cancel all timers (just in case)
for (std::size_t i = 0; i < timers.size(); ++i)
timers[i]->cancel();
io.stop();
std::cout << "\nPOOL DOWN\n";
} <-------------------------------------------- CRASH
catch(...)
{
std::cout << "ERROR";
}
std::cout << "\nEXIT\n";
return 0;
}