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>
15 extern bool fShutdown;
17 template<typename T> class CCheckQueueControl;
19 /** Queue for verifications that have to be performed.
20 * The verifications are represented by a type T, which must provide an
21 * operator(), returning a bool.
23 * One thread (the master) is assumed to push batches of verifications
24 * onto the queue, where they are processed by N-1 worker threads. When
25 * the master is done adding work, it temporarily joins the worker pool
26 * as an N'th worker, until all jobs are done.
28 template<typename T> class CCheckQueue {
30 // Mutex to protect the inner state
33 // Worker threads block on this when out of work
34 std::condition_variable condWorker;
36 // Master thread blocks on this when out of work
37 std::condition_variable condMaster;
39 // Quit method blocks on this until all workers are gone
40 std::condition_variable condQuit;
42 // The queue of elements to be processed.
43 // As the order of booleans doesn't matter, it is used as a LIFO (stack)
46 // The number of workers (including the master) that are idle.
49 // The total number of workers (including the master).
52 // The temporary evaluation result.
55 // Number of verifications that haven't completed yet.
56 // This includes elements that are not anymore in queue, but still in
57 // worker's own batches.
60 // Whether we're shutting down.
63 // The maximum number of elements to be processed in one batch
64 unsigned int nBatchSize;
66 // Internal function that does bulk of the verification work.
67 bool Loop(bool fMaster = false) {
68 std::condition_variable &cond = fMaster ? condMaster : condWorker;
69 std::vector<T> vChecks;
70 vChecks.reserve(nBatchSize);
71 unsigned int nNow = 0;
75 std::unique_lock<std::mutex> lock(mutex);
76 // first do the clean-up of the previous loop run (allowing us to do it in the same critsect)
80 if (nTodo == 0 && !fMaster)
81 // We processed the last element; inform the master he can exit and return the result
82 condMaster.notify_one();
87 // logically, the do loop starts here
88 while (queue.empty()) {
89 if ((fMaster || fQuit) && nTodo == 0) {
92 condQuit.notify_one();
94 // reset the status for new work later
97 // return the current status
101 cond.wait(lock); // wait
104 // Decide how many work units to process now.
105 // * Do not try to do everything at once, but aim for increasingly smaller batches so
106 // all workers finish approximately simultaneously.
107 // * Try to account for idle jobs which will instantly start helping.
108 // * Don't do batches smaller than 1 (duh), or larger than nBatchSize.
109 nNow = std::max(1U, std::min(nBatchSize, (unsigned int)queue.size() / (nTotal + nIdle + 1)));
110 vChecks.resize(nNow);
111 for (unsigned int i = 0; i < nNow; i++) {
112 // We want the lock on the mutex to be as short as possible, so swap jobs from the global
113 // queue to the local batch vector instead of copying.
114 vChecks[i].swap(queue.back());
117 // Check whether we need to do work at all
121 for (T &check : vChecks)
125 } while(true && !fShutdown); // HACK: force queue to shut down
130 // Create a new check queue
131 CCheckQueue(unsigned int nBatchSizeIn) :
132 nIdle(0), nTotal(0), fAllOk(true), nTodo(0), fQuit(false), nBatchSize(nBatchSizeIn) {}
139 // Wait until execution finishes, and return whether all evaluations where succesful.
144 // Add a batch of checks to the queue
145 void Add(std::vector<T> &vChecks) {
146 std::unique_lock<std::mutex> lock(mutex);
147 for (T &check : vChecks) {
148 queue.push_back(T());
149 check.swap(queue.back());
151 nTodo += vChecks.size();
152 if (vChecks.size() == 1)
153 condWorker.notify_one();
154 else if (vChecks.size() > 1)
155 condWorker.notify_all();
158 // Shut the queue down
160 std::unique_lock<std::mutex> lock(mutex);
162 // No need to wake the master, as he will quit automatically when all jobs are
164 condWorker.notify_all();
176 std::unique_lock<std::mutex> lock(mutex);
177 return (nTotal == nIdle && nTodo == 0 && fAllOk == true);
181 /** RAII-style controller object for a CCheckQueue that guarantees the passed
182 * queue is finished before continuing.
184 template<typename T> class CCheckQueueControl {
186 CCheckQueue<T> *pqueue;
190 CCheckQueueControl(CCheckQueue<T> *pqueueIn) : pqueue(pqueueIn), fDone(false) {
191 // passed queue is supposed to be unused, or NULL
192 if (pqueue != nullptr) {
193 bool isIdle = pqueue->IsIdle();
199 if (pqueue == nullptr)
201 bool fRet = pqueue->Wait();
206 void Add(std::vector<T> &vChecks) {
207 if (pqueue != nullptr)
208 pqueue->Add(vChecks);
211 ~CCheckQueueControl() {