make threadpool implementation callback agnostic

This commit is contained in:
Konstantin Käfer
2014-03-03 12:26:04 +01:00
parent b26f3d319b
commit c076da0ae2
3 changed files with 12 additions and 13 deletions

View File

@@ -22,9 +22,10 @@ class Threadpool {
public:
typedef void (*Callback)(void *);
Threadpool(Callback callback, int max_workers = 4);
typedef std::pair<Callback, void *> Task;
Threadpool(int max_workers = 4);
void add(void *data);
void add(Callback callback, void *data);
private:
const int max_workers;
@@ -32,8 +33,7 @@ private:
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
std::forward_list<Worker> workers;
int worker_count = 0;
Callback callback;
std::queue<void *> tasks;
std::queue<Task> tasks;
};
}

View File

@@ -36,7 +36,7 @@ int Request::curl_progress_callback(void *ptr, double dltotal, double dlnow, dou
}
void Request::initialize() {
pool = new llmr::util::Threadpool(Request::request);
pool = new llmr::util::Threadpool();
// curl init
curl_global_init(CURL_GLOBAL_ALL);
@@ -57,7 +57,7 @@ Request::Request(std::string url, std::function<void(platform::Response&)> bg, s
background_function(bg),
foreground_callback(fg) {
assert(pool);
pool->add(this);
pool->add(request, this);
}
void Request::request(void *ptr) {

View File

@@ -2,19 +2,18 @@
using namespace llmr::util;
Threadpool::Threadpool(Callback callback, int max_workers)
: max_workers(max_workers),
callback(callback) {
Threadpool::Threadpool(int max_workers)
: max_workers(max_workers) {
}
void Threadpool::add(void *data) {
void Threadpool::add(Callback callback, void *data) {
if (worker_count < max_workers) {
workers.emplace_front(*this);
worker_count++;
}
pthread_mutex_lock(&mutex);
tasks.push(data);
tasks.push(std::make_pair(callback, data));
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&condition);
}
@@ -37,10 +36,10 @@ void *Threadpool::Worker::loop(void *ptr) {
pthread_mutex_lock(&pool.mutex);
while (true) {
if (pool.tasks.size()) {
void *task = pool.tasks.front();
Threadpool::Task task = pool.tasks.front();
pool.tasks.pop();
pthread_mutex_unlock(&pool.mutex);
pool.callback(task);
task.first(task.second);
pthread_mutex_lock(&pool.mutex);
} else {
pthread_cond_wait(&pool.condition, &pool.mutex);