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 <condition_variable>
13 extern bool fShutdown;
15 template<typename T> class CCheckQueueControl;
17 // Queue for verifications that have to be performed.
18 // The verifications are represented by a type T, which must provide an
19 // operator(), returning a bool.
21 // One thread (the master) is assumed to push batches of verifications
22 // onto the queue, where they are processed by N-1 worker threads. When
23 // the master is done adding work, it temporarily joins the worker pool
24 // as an N'th worker, until all jobs are done.
26 template<typename T> class CCheckQueue {
28 // Mutex to protect the inner state
31 // Worker threads block on this when out of work
32 std::condition_variable condWorker;
34 // Master thread blocks on this when out of work
35 std::condition_variable condMaster;
37 // Quit method blocks on this until all workers are gone
38 std::condition_variable condQuit;
40 // The queue of elements to be processed.
41 // As the order of booleans doesn't matter, it is used as a LIFO (stack)
44 // The number of workers (including the master) that are idle.
47 // The total number of workers (including the master).
50 // The temporary evaluation result.
53 // Number of verifications that haven't completed yet.
54 // This includes elements that are not anymore in queue, but still in
55 // worker's own batches.
58 // Whether we're shutting down.
61 // The maximum number of elements to be processed in one batch
62 unsigned int nBatchSize;
64 // Internal function that does bulk of the verification work.
65 bool Loop(bool fMaster = false) {
66 std::condition_variable &cond = fMaster ? condMaster : condWorker;
67 std::vector<T> vChecks;
68 vChecks.reserve(nBatchSize);
69 unsigned int nNow = 0;
73 std::unique_lock<std::mutex> lock(mutex);
74 // first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
78 if (nTodo == 0 && !fMaster)
79 // We processed the last element; inform the master he can exit and return the result
80 condMaster.notify_one();
85 // logically, the do loop starts here
86 while (queue.empty()) {
87 if ((fMaster || fQuit) && nTodo == 0) {
90 condQuit.notify_one();
92 // reset the status for new work later
95 // return the current status
99 cond.wait(lock); // wait
102 // Decide how many work units to process now.
103 // * Do not try to do everything at once, but aim for increasingly smaller batches so
104 // all workers finish approximately simultaneously.
105 // * Try to account for idle jobs which will instantly start helping.
106 // * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
107 nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
108 vChecks.resize(nNow);
109 for (unsigned int i = 0; i < nNow; i++) {
110 // We want the lock on the mutex to be as short as possible, so swap jobs from the global
111 // queue to the local batch vector instead of copying.
112 vChecks[i].swap(queue.back());
115 // Check whether we need to do work at all
119 for(T &check : vChecks)
123 } while(true && !fShutdown); // HACK: force queue to shut down
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 std::unique_lock<std::mutex> lock(mutex);
145 for(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 std::unique_lock<std::mutex> lock(mutex);
160 // No need to wake the master, as he will quit automatically when all jobs are
162 condWorker.notify_all();
174 std::unique_lock<std::mutex> lock(mutex);
175 return (nTotal == nIdle && nTodo == 0 && fAllOk == true);
179 // RAII-style controller object for a CCheckQueue that guarantees the passed
180 // queue is finished before continuing.
182 template<typename T> class CCheckQueueControl {
184 CCheckQueue<T> *pqueue;
188 CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
189 // passed queue is supposed to be unused, or NULL
190 if (pqueue != nullptr) {
191 bool isIdle = pqueue->IsIdle();
197 if (pqueue == nullptr)
199 bool fRet = pqueue->Wait();
204 void Add(std::vector<T> &vChecks) {
205 if (pqueue != nullptr)
206 pqueue->Add(vChecks);
209 ~CCheckQueueControl() {