erebus

view 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 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 }
19 ThreadPool::~ThreadPool()
20 {
21 quit = true;
22 condvar.notify_all();
24 printf("ThreadPool: waiting for %d worker threads to stop ", num_threads);
25 fflush(stdout);
26 for(int i=0; i<num_threads; i++) {
27 thread[i].join();
28 putchar('.');
29 fflush(stdout);
30 }
31 putchar('\n');
32 }
34 void ThreadPool::add_work(std::function<void ()> func)
35 {
36 std::unique_lock<std::mutex> lock(workq_mutex);
37 workq.push_back(func);
38 }
40 void ThreadPool::thread_func()
41 {
42 std::unique_lock<std::mutex> lock(workq_mutex);
43 for(;;) {
44 if(quit) break;
46 condvar.wait(lock);
48 if(!quit && !workq.empty()) {
49 std::function<void ()> work = workq.front();
50 workq.pop_front();
51 lock.unlock();
53 work();
55 lock.lock();
56 }
57 }
58 }