Add proper per-file copyright notices/licenses and top-level license.
[bluesky.git] / kvstore / workqueue.h
1 #ifndef __WORKQUEUE_H__
2 #define __WORKQUEUE_H__ 1
3
4 #include <boost/thread.hpp>
5 #include <boost/shared_ptr.hpp>
6 #include <queue>
7 #include "util.h"
8
9 using namespace boost;
10 using namespace std;
11
12 namespace bicker
13 {
14     struct interrupted_error : public virtual std::exception { };
15
16     class WorkUnit
17     {
18     public:
19         virtual ~WorkUnit() {};
20         virtual void run() = 0;
21     };
22
23     class WorkQueue
24     {
25     public:
26         WorkQueue();
27         WorkQueue(int thread_count);
28
29         ~WorkQueue();
30
31         shared_ptr<WorkUnit> get();
32         void put(shared_ptr<WorkUnit> work_unit);
33
34     protected:
35         void spawnThread();
36
37     private:
38         class Worker
39         {
40         public:
41             Worker(WorkQueue* queue);
42             void operator()();
43         private:
44             WorkQueue *_queue;
45         };
46
47         int _thread_count;
48         int _min_threads;
49         int _max_threads;
50         mutex _queue_lock;
51         condition_variable _queue_non_empty;
52         queue<shared_ptr<WorkUnit> > _queue;
53         thread_group _threads;
54         volatile bool _running;
55     };
56
57     class TaskNotification
58     {
59     public:
60         TaskNotification();
61
62         void registerTask();
63         void completeTask(bool success = true);
64
65         void waitForComplete();
66
67         bool failCount();
68     private:
69         int                _expected;
70         int                _count;
71         int                _fail_count;
72         mutex              _lock;
73         condition_variable _cond;
74     };
75
76 } // namespace bicker
77
78 #endif