Type cleanups
[invirt/third/libt4.git] / rpc / thr_pool.cc
1 #include "thr_pool.h"
2 #include <stdlib.h>
3 #include <errno.h>
4 #include "lang/verify.h"
5
6 // if blocking, then addJob() blocks when queue is full
7 // otherwise, addJob() simply returns false when queue is full
8 ThrPool::ThrPool(int sz, bool blocking)
9 : nthreads_(sz),blockadd_(blocking),jobq_(100*sz) 
10 {
11         for (int i=0; i<nthreads_; i++)
12         th_.emplace_back(&ThrPool::do_worker, this);
13 }
14
15 // IMPORTANT: this function can be called only when no external thread 
16 // will ever use this thread pool again or is currently blocking on it
17 ThrPool::~ThrPool()
18 {
19         for (int i=0; i<nthreads_; i++)
20                 jobq_.enq(job_t());
21
22         for (int i=0; i<nthreads_; i++)
23         th_[i].join();
24 }
25
26 bool 
27 ThrPool::addJob(const job_t &j)
28 {
29         return jobq_.enq(j,blockadd_);
30 }
31
32 void
33 ThrPool::do_worker()
34 {
35     job_t j;
36         while (1) {
37         jobq_.deq(&j);
38                 if (!j)
39                         break;
40                 j();
41         }
42 }