erebus

annotate liberebus/src/threadpool.cc @ 25:6ef4b10fa468

ops, failed to set num_threads in ThreadPool
author John Tsiombikas <nuclear@member.fsf.org>
date Sat, 31 May 2014 06:21:09 +0300
parents 4336acf8389d
children c8a6fb04fefa
rev   line source
nuclear@24 1 #include "threadpool.h"
nuclear@24 2
nuclear@24 3 ThreadPool::ThreadPool(int num_threads)
nuclear@24 4 {
nuclear@24 5 quit = false;
nuclear@24 6
nuclear@24 7 if(num_threads == -1) {
nuclear@24 8 num_threads = std::thread::hardware_concurrency();
nuclear@24 9 }
nuclear@24 10
nuclear@24 11 printf("creating thread pool with %d threads\n", num_threads);
nuclear@24 12
nuclear@24 13 thread = new std::thread[num_threads];
nuclear@24 14 for(int i=0; i<num_threads; i++) {
nuclear@24 15 thread[i] = std::thread(&ThreadPool::thread_func, this);
nuclear@24 16 }
nuclear@25 17 this->num_threads = num_threads;
nuclear@24 18 }
nuclear@24 19
nuclear@24 20 ThreadPool::~ThreadPool()
nuclear@24 21 {
nuclear@24 22 quit = true;
nuclear@24 23 condvar.notify_all();
nuclear@24 24
nuclear@24 25 printf("ThreadPool: waiting for %d worker threads to stop ", num_threads);
nuclear@24 26 fflush(stdout);
nuclear@24 27 for(int i=0; i<num_threads; i++) {
nuclear@24 28 thread[i].join();
nuclear@24 29 putchar('.');
nuclear@24 30 fflush(stdout);
nuclear@24 31 }
nuclear@24 32 putchar('\n');
nuclear@24 33 }
nuclear@24 34
nuclear@24 35 void ThreadPool::add_work(std::function<void ()> func)
nuclear@24 36 {
nuclear@24 37 std::unique_lock<std::mutex> lock(workq_mutex);
nuclear@24 38 workq.push_back(func);
nuclear@24 39 }
nuclear@24 40
nuclear@24 41 void ThreadPool::thread_func()
nuclear@24 42 {
nuclear@24 43 std::unique_lock<std::mutex> lock(workq_mutex);
nuclear@24 44 for(;;) {
nuclear@24 45 if(quit) break;
nuclear@24 46
nuclear@24 47 condvar.wait(lock);
nuclear@24 48
nuclear@24 49 if(!quit && !workq.empty()) {
nuclear@24 50 std::function<void ()> work = workq.front();
nuclear@24 51 workq.pop_front();
nuclear@24 52 lock.unlock();
nuclear@24 53
nuclear@24 54 work();
nuclear@24 55
nuclear@24 56 lock.lock();
nuclear@24 57 }
nuclear@24 58 }
nuclear@25 59 }