erebus

view 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
line source
1 #include "threadpool.h"
3 ThreadPool::ThreadPool(int num_threads)
4 {
5 quit = false;
7 if(num_threads == -1) {
8 num_threads = std::thread::hardware_concurrency();
9 }
11 printf("creating thread pool with %d threads\n", num_threads);
13 thread = new std::thread[num_threads];
14 for(int i=0; i<num_threads; i++) {
15 thread[i] = std::thread(&ThreadPool::thread_func, this);
16 }
17 this->num_threads = num_threads;
18 }
20 ThreadPool::~ThreadPool()
21 {
22 quit = true;
23 condvar.notify_all();
25 printf("ThreadPool: waiting for %d worker threads to stop ", num_threads);
26 fflush(stdout);
27 for(int i=0; i<num_threads; i++) {
28 thread[i].join();
29 putchar('.');
30 fflush(stdout);
31 }
32 putchar('\n');
33 }
35 void ThreadPool::add_work(std::function<void ()> func)
36 {
37 std::unique_lock<std::mutex> lock(workq_mutex);
38 workq.push_back(func);
39 }
41 void ThreadPool::thread_func()
42 {
43 std::unique_lock<std::mutex> lock(workq_mutex);
44 for(;;) {
45 if(quit) break;
47 condvar.wait(lock);
49 if(!quit && !workq.empty()) {
50 std::function<void ()> work = workq.front();
51 workq.pop_front();
52 lock.unlock();
54 work();
56 lock.lock();
57 }
58 }
59 }