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