Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 70 lines (54 sloc) 1.241 kb
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#include <map>
#include <vector>

#include "background_task_pool.hpp"
#include "foreach.hpp"
#include "thread.hpp"

namespace background_task_pool
{

namespace {

int next_task_id = 0;

struct task {
boost::function<void()> job, on_complete;
boost::shared_ptr<threading::thread> thread;
};

threading::mutex* completed_tasks_mutex = NULL;
std::vector<int> completed_tasks;

std::map<int, task> task_map;

void run_task(boost::function<void()> job, int task_id)
{
job();
threading::lock(*completed_tasks_mutex);
completed_tasks.push_back(task_id);
}

}

manager::manager()
{
completed_tasks_mutex = new threading::mutex;
}

manager::~manager()
{
while(task_map.empty() == false) {
pump();
}
}

void submit(boost::function<void()> job, boost::function<void()> on_complete)
{
task t = { job, on_complete, boost::shared_ptr<threading::thread>(new threading::thread(boost::bind(run_task, job, next_task_id))) };
task_map[next_task_id] = t;
++next_task_id;
}

void pump()
{
std::vector<int> completed;
{
threading::lock(*completed_tasks_mutex);
completed.swap(completed_tasks);
}

foreach(int t, completed) {
task_map[t].on_complete();
task_map.erase(t);
}
}

}
Something went wrong with that request. Please try again.