erebus

diff liberebus/src/threadpool.cc @ 24:4336acf8389d

implemented thread pool. not using it yet.
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 30 May 2014 06:56:44 +0300
parents
children 6ef4b10fa468
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/liberebus/src/threadpool.cc	Fri May 30 06:56:44 2014 +0300
     1.3 @@ -0,0 +1,58 @@
     1.4 +#include "threadpool.h"
     1.5 +
     1.6 +ThreadPool::ThreadPool(int num_threads)
     1.7 +{
     1.8 +	quit = false;
     1.9 +
    1.10 +	if(num_threads == -1) {
    1.11 +		num_threads = std::thread::hardware_concurrency();
    1.12 +	}
    1.13 +
    1.14 +	printf("creating thread pool with %d threads\n", num_threads);
    1.15 +
    1.16 +	thread = new std::thread[num_threads];
    1.17 +	for(int i=0; i<num_threads; i++) {
    1.18 +		thread[i] = std::thread(&ThreadPool::thread_func, this);
    1.19 +	}
    1.20 +}
    1.21 +
    1.22 +ThreadPool::~ThreadPool()
    1.23 +{
    1.24 +	quit = true;
    1.25 +	condvar.notify_all();
    1.26 +
    1.27 +	printf("ThreadPool: waiting for %d worker threads to stop ", num_threads);
    1.28 +	fflush(stdout);
    1.29 +	for(int i=0; i<num_threads; i++) {
    1.30 +		thread[i].join();
    1.31 +		putchar('.');
    1.32 +		fflush(stdout);
    1.33 +	}
    1.34 +	putchar('\n');
    1.35 +}
    1.36 +
    1.37 +void ThreadPool::add_work(std::function<void ()> func)
    1.38 +{
    1.39 +	std::unique_lock<std::mutex> lock(workq_mutex);
    1.40 +	workq.push_back(func);
    1.41 +}
    1.42 +
    1.43 +void ThreadPool::thread_func()
    1.44 +{
    1.45 +	std::unique_lock<std::mutex> lock(workq_mutex);
    1.46 +	for(;;) {
    1.47 +		if(quit) break;
    1.48 +
    1.49 +		condvar.wait(lock);
    1.50 +
    1.51 +		if(!quit && !workq.empty()) {
    1.52 +			std::function<void ()> work = workq.front();
    1.53 +			workq.pop_front();
    1.54 +			lock.unlock();
    1.55 +
    1.56 +			work();
    1.57 +
    1.58 +			lock.lock();
    1.59 +		}
    1.60 +	}
    1.61 +}
    1.62 \ No newline at end of file