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.
11 #include <boost/foreach.hpp>
12 #include <boost/thread/condition_variable.hpp>
13 #include <boost/thread/locks.hpp>
14 #include <boost/thread/mutex.hpp>
16 template<typename T> class CCheckQueueControl;
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.
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.
27 template<typename T> class CCheckQueue {
29 // Mutex to protect the inner state
32 // Worker threads block on this when out of work
33 boost::condition_variable condWorker;
35 // Master thread blocks on this when out of work
36 boost::condition_variable condMaster;
38 // Quit method blocks on this until all workers are gone
39 boost::condition_variable condQuit;
41 // The queue of elements to be processed.
42 // As the order of booleans doesn't matter, it is used as a LIFO (stack)
45 // The number of workers (including the master) that are idle.
48 // The total number of workers (including the master).
51 // The temporary evaluation result.
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.
59 // Whether we're shutting down.
62 // The maximum number of elements to be processed in one batch
63 unsigned int nBatchSize;
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;
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)
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();
86 // logically, the do loop starts here
87 while (queue.empty()) {
88 if ((fMaster || fQuit) && nTodo == 0) {
91 condQuit.notify_one();
93 // reset the status for new work later
96 // return the current status
100 cond.wait(lock); // wait
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());
116 // Check whether we need to do work at all
120 BOOST_FOREACH(T &check, vChecks)
128 // Create a new check queue
129 CCheckQueue(unsigned int nBatchSizeIn) :
130 nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
137 // Wait until execution finishes, and return whether all evaluations where succesful.
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());
149 nTodo += vChecks.size();
150 if (vChecks.size() == 1)
151 condWorker.notify_one();
152 else if (vChecks.size() > 1)
153 condWorker.notify_all();
156 // Shut the queue down
158 boost::unique_lock<boost::mutex> lock(mutex);
160 // No need to wake the master, as he will quit automatically when all jobs are
162 condWorker.notify_all();
168 friend class CCheckQueueControl<T>;
171 /** RAII-style controller object for a CCheckQueue that guarantees the passed
172 * queue is finished before continuing.
174 template<typename T> class CCheckQueueControl {
176 CCheckQueue<T> *pqueue;
180 CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
181 // passed queue is supposed to be unused, or NULL
182 if (pqueue != NULL) {
183 assert(pqueue->nTotal == pqueue->nIdle);
184 assert(pqueue->nTodo == 0);
185 assert(pqueue->fAllOk == true);
192 bool fRet = pqueue->Wait();
197 void Add(std::vector<T> &vChecks) {
199 pqueue->Add(vChecks);
202 ~CCheckQueueControl() {