Acquire CCheckQueue's lock to avoid race condition
[novacoin.git] / src / checkqueue.h
1 // Copyright (c) 2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #ifndef CHECKQUEUE_H
6 #define CHECKQUEUE_H
7
8 #include <algorithm>
9 #include <vector>
10
11 #include <boost/foreach.hpp>
12 #include <boost/thread/condition_variable.hpp>
13 #include <boost/thread/locks.hpp>
14 #include <boost/thread/mutex.hpp>
15
16 template<typename T> class CCheckQueueControl;
17
18 /** Queue for verifications that have to be performed.
19   * The verifications are represented by a type T, which must provide an
20   * operator(), returning a bool.
21   *
22   * One thread (the master) is assumed to push batches of verifications
23   * onto the queue, where they are processed by N-1 worker threads. When
24   * the master is done adding work, it temporarily joins the worker pool
25   * as an N'th worker, until all jobs are done.
26   */
27 template<typename T> class CCheckQueue {
28 private:
29     // Mutex to protect the inner state
30     boost::mutex mutex;
31
32     // Worker threads block on this when out of work
33     boost::condition_variable condWorker;
34
35     // Master thread blocks on this when out of work
36     boost::condition_variable condMaster;
37
38     // Quit method blocks on this until all workers are gone
39     boost::condition_variable condQuit;
40
41     // The queue of elements to be processed.
42     // As the order of booleans doesn't matter, it is used as a LIFO (stack)
43     std::vector<T> queue;
44
45     // The number of workers (including the master) that are idle.
46     int nIdle;
47
48     // The total number of workers (including the master).
49     int nTotal;
50
51     // The temporary evaluation result.
52     bool fAllOk;
53
54     // Number of verifications that haven't completed yet.
55     // This includes elements that are not anymore in queue, but still in
56     // worker's own batches.
57     unsigned int nTodo;
58
59     // Whether we're shutting down.
60     bool fQuit;
61
62     // The maximum number of elements to be processed in one batch
63     unsigned int nBatchSize;
64
65     // Internal function that does bulk of the verification work.
66     bool Loop(bool fMaster = false) {
67         boost::condition_variable &cond = fMaster ? condMaster : condWorker;
68         std::vector<T> vChecks;
69         vChecks.reserve(nBatchSize);
70         unsigned int nNow = 0;
71         bool fOk = true;
72         do {
73             {
74                 boost::unique_lock<boost::mutex> lock(mutex);
75                 // first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
76                 if (nNow) {
77                     fAllOk &= fOk;
78                     nTodo -= nNow;
79                     if (nTodo == 0 && !fMaster)
80                         // We processed the last element; inform the master he can exit and return the result
81                         condMaster.notify_one();
82                 } else {
83                     // first iteration
84                     nTotal++;
85                 }
86                 // logically, the do loop starts here
87                 while (queue.empty()) {
88                     if ((fMaster || fQuit) && nTodo == 0) {
89                         nTotal--;
90                         if (nTotal==0)
91                             condQuit.notify_one();
92                         bool fRet = fAllOk;
93                         // reset the status for new work later
94                         if (fMaster)
95                             fAllOk = true;
96                         // return the current status
97                         return fRet;
98                     }
99                     nIdle++;
100                     cond.wait(lock); // wait
101                     nIdle--;
102                 }
103                 // Decide how many work units to process now.
104                 // * Do not try to do everything at once, but aim for increasingly smaller batches so
105                 //   all workers finish approximately simultaneously.
106                 // * Try to account for idle jobs which will instantly start helping.
107                 // * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
108                 nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
109                 vChecks.resize(nNow);
110                 for (unsigned int i = 0; i < nNow; i++) {
111                      // We want the lock on the mutex to be as short as possible, so swap jobs from the global
112                      // queue to the local batch vector instead of copying.
113                      vChecks[i].swap(queue.back());
114                      queue.pop_back();
115                 }
116                 // Check whether we need to do work at all
117                 fOk = fAllOk;
118             }
119             // execute work
120             BOOST_FOREACH(T &check, vChecks)
121                 if (fOk)
122                     fOk = check();
123             vChecks.clear();
124         } while(true);
125     }
126
127 public:
128     // Create a new check queue
129     CCheckQueue(unsigned int nBatchSizeIn) :
130         nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
131
132     // Worker thread
133     void Thread() {
134         Loop();
135     }
136
137     // Wait until execution finishes, and return whether all evaluations where succesful.
138     bool Wait() {
139         return Loop(true);
140     }
141
142     // Add a batch of checks to the queue
143     void Add(std::vector<T> &vChecks) {
144         boost::unique_lock<boost::mutex> lock(mutex);
145         BOOST_FOREACH(T &check, vChecks) {
146             queue.push_back(T());
147             check.swap(queue.back());
148         }
149         nTodo += vChecks.size();
150         if (vChecks.size() == 1)
151             condWorker.notify_one();
152         else if (vChecks.size() > 1)
153             condWorker.notify_all();
154     }
155
156     // Shut the queue down
157     void Quit() {
158         boost::unique_lock<boost::mutex> lock(mutex);
159         fQuit = true;
160         // No need to wake the master, as he will quit automatically when all jobs are
161         // done.
162         condWorker.notify_all(); 
163
164         while (nTotal > 0)
165             condQuit.wait(lock);
166     }
167
168     ~CCheckQueue() {
169         Quit();
170     }
171
172     bool IsIdle()
173     {
174         boost::unique_lock<boost::mutex> lock(mutex);
175         return (nTotal == nIdle && nTodo == 0 && fAllOk == true);
176     }
177 };
178
179 /** RAII-style controller object for a CCheckQueue that guarantees the passed
180  *  queue is finished before continuing.
181  */
182 template<typename T> class CCheckQueueControl {
183 private:
184     CCheckQueue<T> *pqueue;
185     bool fDone;
186
187 public:
188     CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
189         // passed queue is supposed to be unused, or NULL
190         if (pqueue != NULL) {
191             bool isIdle = pqueue->IsIdle();
192             assert(isIdle);
193         }
194     }
195
196     bool Wait() {
197         if (pqueue == NULL)
198             return true;
199         bool fRet = pqueue->Wait();
200         fDone = true;
201         return fRet;
202     }
203
204     void Add(std::vector<T> &vChecks) {
205         if (pqueue != NULL)
206             pqueue->Add(vChecks);
207     }
208
209     ~CCheckQueueControl() {
210         if (!fDone)
211             Wait();
212     }
213 };
214
215 #endif