Debian Codegraph @

src/dmlc-core/include/dmlc/threadediter.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2015 by Contributors
3 * \file threadediter.h
4 * \brief thread backed iterator that can be used to implement
5 * general thread-based pipeline such as prefetch and pre-computation
6 * To use the functions in this header, C++11 is required
7 * \author Tianqi Chen
8 */
9 #ifndef DMLC_THREADEDITER_H_
10 #define DMLC_THREADEDITER_H_
11 // defines DMLC_USE_CXX11
12 #include "./base.h"
13 // this code depends on c++11
14 #if DMLC_ENABLE_STD_THREAD
15 #include <atomic>
16 #include <condition_variable>
17 #include <functional>
18 #include <memory>
19 #include <mutex>
20 #include <queue>
21 #include <thread>
22 #include <utility>
23
24 #include "./data.h"
25 #include "./logging.h"
26
27 namespace dmlc {
28
29 /*!
30 * \brief Wrapper class to manage std::thread; uses RAII pattern to automatically
31 * join std::thread upon destruction
32 */
33 class ScopedThread {
34 public:
35 /*!
36 * \brief constructor
37 * \param thread thread to manage
38 */
39 explicit ScopedThread(std::thread thread) : thread_(std::move(thread)) {
40 if (!thread_.joinable()) {
41 throw std::logic_error("No thread");
42 }
43 }
44 // destructor: join upon destruction
45 virtual ~ScopedThread() {
46 thread_.join();
47 }
48 // copy assignment and construction are not allowed
49 ScopedThread(const ScopedThread &) = delete;
50 ScopedThread &operator=(const ScopedThread &) = delete;
51
52 private:
53 std::thread thread_;
54 };
55
56 /*!
57 * \brief a iterator that was backed by a thread
58 * to pull data eagerly from a single producer into a bounded buffer
59 * the consumer can pull the data at its own rate
60 *
61 * NOTE: thread concurrency cost time, make sure to store big blob of data in DType
62 *
63 * Usage example:
64 * \code
65 * ThreadedIter<DType> iter;
66 * iter.Init(&producer);
67 * // the following code can be in parallel
68 * DType *dptr;
69 * while (iter.Next(&dptr)) {
70 * // do something on dptr
71 * // recycle the space
72 * iter.Recycle(&dptr);
73 * }
74 * \endcode
75 * \tparam DType the type of data blob we support
76 */
77 template <typename DType>
78 class ThreadedIter : public DataIter<DType> {
79 public:
80 /*!
81 * \brief producer class interface
82 * that threaditer used as source to
83 * preduce the content
84 */
85 class Producer {
86 public:
87 // virtual destructor
88 virtual ~Producer() = default;
89 /*! \brief reset the producer to beginning */
90 virtual void BeforeFirst() {
91 NotImplemented();
92 }
93 /*!
94 * \brief load the data content into DType,
95 * the caller can pass in NULL or an existing address
96 * when inout_dptr is NULL:
97 * producer need to allocate a DType and fill the content
98 * when inout_dptr is specified
99 * producer takes need to fill the content into address
100 * specified inout_dptr, or delete the one and create a new one
101 *
102 * \param inout_dptr used to pass in the data holder cell
103 * and return the address of the cell filled
104 * \return true if there is next record, false if we reach the end
105 */
106 virtual bool Next(DType **inout_dptr) = 0;
107 };
108 /*!
109 * \brief constructor
110 * \param max_capacity maximum capacity of the queue
111 */
112 explicit ThreadedIter(size_t max_capacity = 8)
113 : producer_(nullptr),
114 producer_thread_(nullptr),
115 max_capacity_(max_capacity),
116 nwait_consumer_(0),
117 nwait_producer_(0),
118 out_data_(NULL) {}
119 /*! \brief destructor */
120 virtual ~ThreadedIter(void) {
121 this->Destroy();
122 }
123 /*!
124 * \brief destroy all the related resources
125 * this is equivalent to destructor, can be used
126 * to destroy the threaditer when user think it is
127 * appropriate, it is safe to call this multiple times
128 */
129 inline void Destroy(void);
130 /*!
131 * \brief set maximum capacity of the queue
132 * \param max_capacity maximum capacity of the queue
133 */
134 inline void set_max_capacity(size_t max_capacity) {
135 max_capacity_ = max_capacity;
136 }
137 /*!
138 * \brief initialize the producer and start the thread can only be
139 * called once
140 * \param producer pointer to the producer
141 */
142 inline void Init(std::shared_ptr<Producer> producer);
143 /*!
144 * \brief initialize the producer and start the thread
145 * pass in two function(closure) of producer to represent the producer
146 * the beforefirst function is optional, and defaults to not implemented
147 * NOTE: the closure must remain valid until the ThreadedIter destructs
148 * \param next the function called to get next element, see Producer.Next
149 * \param beforefirst the function to call to reset the producer, see Producer.BeforeFirst
150 */
151 inline void Init(
152 std::function<bool(DType **)> next, std::function<void()> beforefirst = NotImplemented);
153 /*!
154 * \brief get the next data, this function is threadsafe
155 * \param out_dptr used to hold the pointer to the record
156 * after the function call, the caller takes ownership of the pointer
157 * the caller can call recycle to return ownership back to the threaditer
158 * so that the pointer can be re-used
159 * \return true if there is next record, false if we reach the end
160 * \sa Recycle
161 */
162 inline bool Next(DType **out_dptr);
163 /*!
164 * \brief recycle the data cell, this function is threadsafe
165 * the threaditer can reuse the data cell for future data loading
166 * \param inout_dptr pointer to the dptr to recycle, after the function call
167 * the content of inout_dptr will be set to NULL
168 */
169 inline void Recycle(DType **inout_dptr);
170
171 /*!
172 * \brief Rethrows exception which is set by the producer
173 */
174 inline void ThrowExceptionIfSet(void);
175
176 /*!
177 * \brief clears exception_ptr, called from Init
178 */
179 inline void ClearException(void);
180
181 /*!
182 * \brief adapt the iterator interface's Next
183 * NOTE: the call to this function is not threadsafe
184 * use the other Next instead
185 * \return true if there is next record, false if we reach the end
186 */
187 virtual bool Next(void) override {
188 if (out_data_ != NULL) {
189 this->Recycle(&out_data_);
190 }
191 if (Next(&out_data_)) {
192 return true;
193 } else {
194 return false;
195 }
196 }
197 /*!
198 * \brief adapt the iterator interface's Value
199 * NOTE: the call to this function is not threadsafe
200 * use the other Next instead
201 */
202 virtual const DType &Value(void) const override {
203 CHECK(out_data_ != NULL) << "Calling Value at beginning or end?";
204 return *out_data_;
205 }
206 /*! \brief set the iterator before first location */
207 virtual void BeforeFirst(void) override {
208 ThrowExceptionIfSet();
209 std::unique_lock<std::mutex> lock(mutex_);
210 if (out_data_ != NULL) {
211 free_cells_.push(out_data_);
212 out_data_ = NULL;
213 }
214 if (producer_sig_.load(std::memory_order_acquire) == kDestroy) {
215 return;
216 }
217
218 producer_sig_.store(kBeforeFirst, std::memory_order_release);
219 CHECK(!producer_sig_processed_.load(std::memory_order_acquire));
220 if (nwait_producer_ != 0) {
221 producer_cond_.notify_one();
222 }
223 CHECK(!producer_sig_processed_.load(std::memory_order_acquire));
224 // wait until the request has been processed
225 consumer_cond_.wait(
226 lock, [this]() { return producer_sig_processed_.load(std::memory_order_acquire); });
227 producer_sig_processed_.store(false, std::memory_order_release);
228 bool notify = nwait_producer_ != 0 && !produce_end_;
229 lock.unlock();
230 // notify producer, in case they are waiting for the condition.
231 if (notify) {
232 producer_cond_.notify_one();
233 }
234 ThrowExceptionIfSet();
235 }
236
237 private:
238 /*! \brief not support BeforeFirst */
239 inline static void NotImplemented(void) {
240 LOG(FATAL) << "BeforeFirst is not supported";
241 }
242 /*! \brief signals send to producer */
243 enum Signal { kProduce, kBeforeFirst, kDestroy };
244 /*! \brief producer class */
245 // Producer *producer_owned_;
246 std::shared_ptr<Producer> producer_;
247
248 /*! \brief signal to producer */
249 std::atomic<Signal> producer_sig_;
250 /*! \brief whether the special signal other than kProduce is procssed */
251 std::atomic<bool> producer_sig_processed_;
252 /*! \brief thread that runs the producer */
253 std::unique_ptr<ScopedThread> producer_thread_;
254 /*! \brief whether produce ends */
255 std::atomic<bool> produce_end_;
256 /*! \brief maximum queue size */
257 size_t max_capacity_;
258 /*! \brief internal mutex */
259 std::mutex mutex_;
260 /*! brief internal mutex for exceptions */
261 std::mutex mutex_exception_;
262 /*! \brief number of consumer waiting */
263 unsigned nwait_consumer_;
264 /*! \brief number of producer waiting */
265 unsigned nwait_producer_;
266 /*! \brief conditional variable for producer thread */
267 std::condition_variable producer_cond_;
268 /*! \brief conditional variable for consumer threads */
269 std::condition_variable consumer_cond_;
270 /*! \brief the current output cell */
271 DType *out_data_;
272 /*! \brief internal queue of producer */
273 std::queue<DType *> queue_;
274 /*! \brief free cells that can be used */
275 std::queue<DType *> free_cells_;
276 /*! \brief holds a reference to iterator exception thrown in spawned threads */
277 std::exception_ptr iter_exception_{nullptr};
278 };
279
280 // implementation of functions
281 template <typename DType>
282 inline void ThreadedIter<DType>::Destroy(void) {
283 if (producer_thread_) {
284 {
285 // lock the mutex
286 std::lock_guard<std::mutex> lock(mutex_);
287 // send destroy signal
288 producer_sig_.store(kDestroy, std::memory_order_release);
289 if (nwait_producer_ != 0) {
290 producer_cond_.notify_one();
291 }
292 }
293 producer_thread_.reset(nullptr);
294 }
295 // end of critical region
296 // now the slave thread should exit
297 while (free_cells_.size() != 0) {
298 delete free_cells_.front();
299 free_cells_.pop();
300 }
301 while (queue_.size() != 0) {
302 delete queue_.front();
303 queue_.pop();
304 }
305 if (producer_ != NULL) {
306 producer_.reset();
307 }
308 if (out_data_ != NULL) {
309 delete out_data_;
310 out_data_ = NULL;
311 }
312 }
313
314 template <typename DType>
315 inline void ThreadedIter<DType>::Init(std::shared_ptr<Producer> producer) {
316 CHECK(producer_ == NULL) << "can only call Init once";
317 auto next = [producer](DType **dptr) { return producer->Next(dptr); };
318 auto beforefirst = [producer]() { producer->BeforeFirst(); };
319 this->Init(next, beforefirst);
320 }
321
322 template <typename DType>
323 inline void ThreadedIter<DType>::Init(
324 std::function<bool(DType **)> next, std::function<void()> beforefirst) {
325 producer_sig_.store(kProduce, std::memory_order_release);
326 producer_sig_processed_.store(false, std::memory_order_release);
327 produce_end_.store(false, std::memory_order_release);
328 ClearException();
329 // procedure running in prodcuer
330 // run producer thread
331 auto producer_fun = [this, next, beforefirst]() {
332 while (true) {
333 try {
334 DType *cell = NULL;
335 {
336 // lockscope
337 std::unique_lock<std::mutex> lock(mutex_);
338 ++this->nwait_producer_;
339 producer_cond_.wait(lock, [this]() {
340 if (producer_sig_.load(std::memory_order_acquire) == kProduce) {
341 bool ret = !produce_end_.load(std::memory_order_acquire)
342 && (queue_.size() < max_capacity_ || free_cells_.size() != 0);
343 return ret;
344 } else {
345 return true;
346 }
347 });
348 --this->nwait_producer_;
349 if (producer_sig_.load(std::memory_order_acquire) == kProduce) {
350 if (free_cells_.size() != 0) {
351 cell = free_cells_.front();
352 free_cells_.pop();
353 }
354 } else if (producer_sig_.load(std::memory_order_acquire) == kBeforeFirst) {
355 // reset the producer
356 beforefirst();
357 // cleanup the queue
358 while (queue_.size() != 0) {
359 free_cells_.push(queue_.front());
360 queue_.pop();
361 }
362 // reset the state
363 produce_end_.store(false, std::memory_order_release);
364 producer_sig_processed_.store(true, std::memory_order_release);
365 producer_sig_.store(kProduce, std::memory_order_release);
366 // notify consumer that all the process as been done.
367 lock.unlock();
368 consumer_cond_.notify_all();
369 continue;
370 } else {
371 // destroy the thread
372 DCHECK(producer_sig_.load(std::memory_order_acquire) == kDestroy);
373 producer_sig_processed_.store(true, std::memory_order_release);
374 produce_end_.store(true, std::memory_order_release);
375 lock.unlock();
376 consumer_cond_.notify_all();
377 return;
378 }
379 } // end of lock scope
380 // now without lock
381 produce_end_.store(!next(&cell), std::memory_order_release);
382 DCHECK(cell != NULL || produce_end_.load(std::memory_order_acquire));
383 bool notify;
384 {
385 // lockscope
386 std::lock_guard<std::mutex> lock(mutex_);
387 if (!produce_end_.load(std::memory_order_acquire)) {
388 queue_.push(cell);
389 } else {
390 if (cell != NULL) {
391 free_cells_.push(cell);
392 }
393 }
394 // put things into queue
395 notify = nwait_consumer_ != 0;
396 }
397 if (notify) {
398 consumer_cond_.notify_all();
399 }
400 } catch (std::exception &e) {
401 // Shouldn't throw exception in destructor
402 DCHECK(producer_sig_.load(std::memory_order_acquire) != kDestroy);
403 {
404 std::lock_guard<std::mutex> lock(mutex_exception_);
405 if (!iter_exception_) {
406 iter_exception_ = std::current_exception();
407 }
408 }
409 bool next_notify = false;
410 {
411 std::unique_lock<std::mutex> lock(mutex_);
412 if (producer_sig_.load(std::memory_order_acquire) == kBeforeFirst) {
413 while (queue_.size() != 0) {
414 free_cells_.push(queue_.front());
415 queue_.pop();
416 }
417 produce_end_.store(true, std::memory_order_release);
418 producer_sig_processed_.store(true, std::memory_order_release);
419 lock.unlock();
420 consumer_cond_.notify_all();
421 } else if (producer_sig_.load(std::memory_order_acquire) == kProduce) {
422 produce_end_.store(true, std::memory_order_release);
423 next_notify = nwait_consumer_ != 0;
424 lock.unlock();
425 if (next_notify) {
426 consumer_cond_.notify_all();
427 }
428 }
429 }
430 return;
431 }
432 }
433 };
434 producer_thread_.reset(new ScopedThread{std::thread(producer_fun)});
435 }
436
437 template <typename DType>
438 inline bool ThreadedIter<DType>::Next(DType **out_dptr) {
439 if (producer_sig_.load(std::memory_order_acquire) == kDestroy) {
440 return false;
441 }
442 ThrowExceptionIfSet();
443 std::unique_lock<std::mutex> lock(mutex_);
444 CHECK(producer_sig_.load(std::memory_order_acquire) == kProduce)
445 << "Make sure you call BeforeFirst not inconcurrent with Next!";
446 ++nwait_consumer_;
447 consumer_cond_.wait(lock,
448 [this]() { return queue_.size() != 0 || produce_end_.load(std::memory_order_acquire); });
449 --nwait_consumer_;
450 if (queue_.size() != 0) {
451 *out_dptr = queue_.front();
452 queue_.pop();
453 bool notify = nwait_producer_ != 0 && !produce_end_.load(std::memory_order_acquire);
454 lock.unlock();
455 if (notify) {
456 producer_cond_.notify_one();
457 }
458
459 ThrowExceptionIfSet();
460 return true;
461 } else {
462 CHECK(produce_end_.load(std::memory_order_acquire));
463 lock.unlock();
464
465 ThrowExceptionIfSet();
466 return false;
467 }
468 }
469
470 template <typename DType>
471 inline void ThreadedIter<DType>::Recycle(DType **inout_dptr) {
472 bool notify;
473 ThrowExceptionIfSet();
474 {
475 std::lock_guard<std::mutex> lock(mutex_);
476 free_cells_.push(*inout_dptr);
477 *inout_dptr = NULL;
478 notify = nwait_producer_ != 0 && !produce_end_.load(std::memory_order_acquire);
479 }
480 if (notify) {
481 producer_cond_.notify_one();
482 }
483 ThrowExceptionIfSet();
484 }
485
486 template <typename DType>
487 inline void ThreadedIter<DType>::ThrowExceptionIfSet(void) {
488 std::exception_ptr tmp_exception{nullptr};
489 {
490 std::lock_guard<std::mutex> lock(mutex_exception_);
491 if (iter_exception_) {
492 tmp_exception = iter_exception_;
493 }
494 }
495 if (tmp_exception) {
496 try {
497 std::rethrow_exception(tmp_exception);
498 } catch (std::exception &exc) {
499 LOG(FATAL) << exc.what();
500 }
501 }
502 }
503
504 template <typename DType>
505 inline void ThreadedIter<DType>::ClearException(void) {
506 std::lock_guard<std::mutex> lock(mutex_exception_);
507 iter_exception_ = nullptr;
508 }
509
510 } // namespace dmlc
511 #endif // DMLC_USE_CXX11
512 #endif // DMLC_THREADEDITER_H_