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 // The queue of elements to be processed.
39 // As the order of booleans doesn't matter, it is used as a LIFO (stack)
42 // The number of workers (including the master) that are idle.
45 // The total number of workers (including the master).
48 // The temporary evaluation result.
51 // Number of verifications that haven't completed yet.
52 // This includes elements that are not anymore in queue, but still in
53 // worker's own batches.
56 // Whether we're shutting down.
59 // The maximum number of elements to be processed in one batch
60 unsigned int nBatchSize;
62 // Internal function that does bulk of the verification work.
63 bool Loop(bool fMaster = false) {
64 boost::condition_variable &cond = fMaster ? condMaster : condWorker;
65 std::vector<T> vChecks;
66 vChecks.reserve(nBatchSize);
67 unsigned int nNow = 0;
71 boost::unique_lock<boost::mutex> lock(mutex);
72 // first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
76 if (nTodo == 0 && !fMaster)
77 // We processed the last element; inform the master he can exit and return the result
78 condMaster.notify_one();
83 // logically, the do loop starts here
84 while (queue.empty()) {
85 if ((fMaster || fQuit) && nTodo == 0) {
88 // reset the status for new work later
91 // return the current status
95 cond.wait(lock); // wait
98 // Decide how many work units to process now.
99 // * Do not try to do everything at once, but aim for increasingly smaller batches so
100 // all workers finish approximately simultaneously.
101 // * Try to account for idle jobs which will instantly start helping.
102 // * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
103 nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
104 vChecks.resize(nNow);
105 for (unsigned int i = 0; i < nNow; i++) {
106 // We want the lock on the mutex to be as short as possible, so swap jobs from the global
107 // queue to the local batch vector instead of copying.
108 vChecks[i].swap(queue.back());
111 // Check whether we need to do work at all
115 BOOST_FOREACH(T &check, vChecks)
123 // Create a new check queue
124 CCheckQueue(unsigned int nBatchSizeIn) :
125 nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
132 // Wait until execution finishes, and return whether all evaluations where succesful.
137 // Add a batch of checks to the queue
138 void Add(std::vector<T> &vChecks) {
139 boost::unique_lock<boost::mutex> lock(mutex);
140 BOOST_FOREACH(T &check, vChecks) {
141 queue.push_back(T());
142 check.swap(queue.back());
144 nTodo += vChecks.size();
145 if (vChecks.size() == 1)
146 condWorker.notify_one();
147 else if (vChecks.size() > 1)
148 condWorker.notify_all();
154 friend class CCheckQueueControl<T>;
157 /** RAII-style controller object for a CCheckQueue that guarantees the passed
158 * queue is finished before continuing.
160 template<typename T> class CCheckQueueControl {
162 CCheckQueue<T> *pqueue;
166 CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
167 // passed queue is supposed to be unused, or NULL
168 if (pqueue != NULL) {
169 assert(pqueue->nTotal == pqueue->nIdle);
170 assert(pqueue->nTodo == 0);
171 assert(pqueue->fAllOk == true);
178 bool fRet = pqueue->Wait();
183 void Add(std::vector<T> &vChecks) {
185 pqueue->Add(vChecks);
188 ~CCheckQueueControl() {
194 #endif // CHECKQUEUE_H