Debian Codegraph @

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

raw symbols SCIP
1 /*!
2 * Copyright (c) 2017 by Contributors
3 * \file thread_group.h
4 * \brief Thread and synchronization primitives and lifecycle management
5 */
6 #ifndef DMLC_THREAD_GROUP_H_
7 #define DMLC_THREAD_GROUP_H_
8
9 #include <memory>
10 #include <mutex>
11 #include <set>
12 #include <string>
13 #include <thread>
14 #include <unordered_map>
15 #include <unordered_set>
16 #include <utility>
17
18 #include <dmlc/blockingconcurrentqueue.h>
19 #include <dmlc/concurrentqueue.h>
20 #include <dmlc/logging.h>
21 #if defined(DMLC_USE_CXX14) || __cplusplus > 201103L /* C++14 */
22 #include <shared_mutex>
23 #endif
24 #include <condition_variable>
25 #ifdef __linux__
26 #include <sys/syscall.h>
27 #include <unistd.h>
28 #endif
29
30 namespace dmlc {
31
32 /*!
33 * \brief Simple manual-reset event gate which remains open after signalled
34 */
35 class ManualEvent {
36 public:
37 ManualEvent() : signaled_(false) {}
38
39 /*!
40 * \brief Wait for the object to become signaled. If the object
41 * is already in the signaled state and reset() has not been called, then no wait will occur
42 */
43 void wait() {
44 std::unique_lock<std::mutex> lock(mutex_);
45 if (!signaled_) {
46 condition_variable_.wait(lock);
47 }
48 }
49
50 /*!
51 * \brief Set this object's state to signaled (wait() will release or pass through)
52 */
53 void signal() {
54 signaled_ = true;
55 std::unique_lock<std::mutex> lk(mutex_);
56 condition_variable_.notify_all();
57 }
58
59 /*!
60 * \brief Manually reset this object's state to unsignaled (wait() will block)
61 */
62 void reset() {
63 std::unique_lock<std::mutex> lk(mutex_);
64 signaled_ = false;
65 }
66
67 private:
68 /*! \brief Internal mutex to protect condition variable and signaled_ variable */
69 std::mutex mutex_;
70 /*! \brief Internal condition variable */
71 std::condition_variable condition_variable_;
72 /*! \brief lockfree signal state check */
73 std::atomic<bool> signaled_;
74 };
75
76 #if defined(DMLC_USE_CXX14) || __cplusplus > 201103L /* C++14 */
77 /*! \brief Mutex which can be read-locked and write-locked */
78 using SharedMutex = std::shared_timed_mutex;
79 /*! \brief Write lock, disallows both reads and writes */
80 using WriteLock = std::unique_lock<SharedMutex>;
81 /*! \brief Read lock, allows concurrent data reads */
82 using ReadLock = std::shared_lock<SharedMutex>;
83 #else
84 /*! \brief Standard mutex for C++ < 14 */
85 using SharedMutex = std::recursive_mutex;
86 /*! \brief Standard unique lock for C++ < 14 */
87 using WriteLock = std::unique_lock<SharedMutex>;
88 /*! \brief Standard unique lock for C++ < 14 */
89 using ReadLock = std::unique_lock<SharedMutex>;
90 #endif
91
92 /*!
93 * \brief Thread lifecycle management group
94 * \note See gtest unit tests Syc.* for a usage examples
95 */
96 class ThreadGroup {
97 public:
98 /*!
99 * \brief Lifecycle-managed thread (used by ThreadGroup)
100 * \note See gtest unit tests Syc.* for a usage examples
101 */
102 class Thread {
103 public:
104 /*! \brief Shared pointer type for readability */
105 using SharedPtr = std::shared_ptr<Thread>;
106
107 /*!
108 * \brief Constructor
109 * \param threadName User-defined name of the thread. must be unique per ThreadGroup
110 * \param owner The ThreadGroup object managing the lifecycle of this thread
111 * \param thrd Optionally-assigned std::thread object associated with this Thread class
112 */
113 Thread(std::string threadName, ThreadGroup *owner, std::thread *thrd = nullptr)
114 : name_(std::move(threadName)),
115 thread_(thrd),
116 ready_event_(std::make_shared<ManualEvent>()),
117 start_event_(std::make_shared<ManualEvent>()),
118 owner_(owner),
119 shutdown_requested_(false),
120 auto_remove_(false) {
121 CHECK_NOTNULL(owner);
122 }
123
124 /*!
125 * \brief Destructor with cleanup
126 */
127 virtual ~Thread() {
128 const bool self_delete = is_current_thread();
129 if (!self_delete) {
130 request_shutdown();
131 internal_join(true);
132 }
133 WriteLock guard(thread_mutex_);
134 if (thread_.load()) {
135 std::thread *thrd = thread_.load();
136 thread_ = nullptr;
137 if (self_delete) {
138 thrd->detach();
139 }
140 delete thrd;
141 }
142 }
143
144 /*!
145 * \brief Name of the thread
146 * \return Pointer to the thread name's string
147 * \note This shoul ndly be used as immediate for the sacope of the
148 * shared pointer pointing to this object
149 */
150 const char *name() const {
151 return name_.c_str();
152 }
153
154 /*!
155 * \brief Launch the given Thread object
156 * \tparam StartFunction Function type for the thread 'main' function
157 * \tparam Args Arguments to pass to the thread 'main' function
158 * \param pThis Shared pointer for the managed thread to launch
159 * \param autoRemove if true, automatically remove this Thread object from the
160 * ThreadGroup owner upon exit
161 * \param start_function The Thread's 'main' function
162 * \param args Arguments to pass to the Thread's 'main' function
163 * \return true if the thread was successfully created and added to the ThreadGroup
164 * If false is returned, the thread may have already been started, but if something
165 * went wrong (ie duplicte thread name for the ThreadGroup), then
166 * request_shutdown() will have been been called on the running thread
167 */
168 template <typename StartFunction, typename... Args>
169 static bool launch(
170 std::shared_ptr<Thread> pThis, bool autoRemove, StartFunction start_function, Args... args);
171
172 /*!
173 * \brief Check if this class represents the currently running thread (self)
174 * \return true if the current running thread belongs to this class
175 */
176 bool is_current_thread() const {
177 ReadLock guard(thread_mutex_);
178 return thread_.load() ? (thread_.load()->get_id() == std::this_thread::get_id()) : false;
179 }
180
181 /*!
182 * \brief Signal to this thread that a thread shutdown/exit is requested.
183 * \note This is a candidate for overrise in a derived class which may trigger shutdown
184 * by means other than a boolean (ie condition variable, SimpleManualkEvent, etc).
185 */
186 virtual void request_shutdown() {
187 shutdown_requested_ = true;
188 }
189
190 /*!
191 * \brief Check whether shutdown has been requested (request_shutdown() was called)
192 * \return true if shutdown was requested.
193 * \note This may be overriden to match an overriden to match an overriden 'request_shutdown()',
194 * for instance.
195 */
196 virtual bool is_shutdown_requested() const {
197 return shutdown_requested_.load();
198 }
199
200 /*!
201 * \brief Check whether the thread is set to auto-remove itself from the ThreadGroup owner
202 * when exiting
203 * \return true if the thread will auto-remove itself from the ThreadGroup owner
204 * when exiting
205 */
206 bool is_auto_remove() const {
207 return auto_remove_;
208 }
209
210 /*!
211 * \brief Make the thread joinable (by removing the auto_remove flag)
212 * \warning Care should be taken not to cause a race condition between this call
213 * and parallel execution of this thread auto-removing itself
214 */
215 void make_joinable() {
216 auto_remove_ = false;
217 }
218
219 /*!
220 * \brief Check whether the thread is joinable
221 * \return true if the thread is joinable
222 */
223 bool joinable() const {
224 if (thread_.load()) {
225 CHECK_EQ(auto_remove_, false);
226 // be checked by searching the group or exit event.
227 return thread_.load()->joinable();
228 }
229 return false;
230 }
231
232 /*!
233 * \brief Thread join
234 * \note join() may not be called on auto-remove threads
235 */
236 void join() {
237 internal_join(false);
238 }
239
240 /*!
241 * \brief Get this thread's id
242 * \return this thread's id
243 */
244 std::thread::id get_id() const {
245 return thread_.load()->get_id();
246 }
247
248 private:
249 /*!
250 * \brief Internal join function
251 * \param auto_remove_ok Whether to allow join on an auto-remove thread
252 */
253 void internal_join(bool auto_remove_ok) {
254 ReadLock guard(thread_mutex_);
255 // should be careful calling (or any function externally) this when in
256 // auto-remove mode
257 if (thread_.load() && thread_.load()->get_id() != std::thread::id()) {
258 std::thread::id someId;
259 if (!auto_remove_ok) {
260 CHECK_EQ(auto_remove_, false);
261 }
262 CHECK_NOTNULL(thread_.load());
263 if (thread_.load()->joinable()) {
264 thread_.load()->join();
265 } else {
266 LOG(WARNING) << "Thread " << name_ << " ( " << thread_.load()->get_id()
267 << " ) not joinable";
268 }
269 }
270 }
271
272 /*!
273 * \brief Thread bootstrapping and teardown wrapper
274 * \tparam StartFunction Thread's "main" function
275 * \tparam Args Argument types to be passed to the start_function
276 * \param pThis Shared pointer to the Thread object to operate upon
277 * \param start_function Thread's "main" function (i.e. passed to launch())
278 * \param args Arguments to be passed to the start_function
279 * \return The thread's return code
280 */
281 template <typename StartFunction, typename... Args>
282 static int entry_and_exit_f(
283 std::shared_ptr<Thread> pThis, StartFunction start_function, Args... args);
284 /*! \brief Thread name */
285 std::string name_;
286 /*! \brief Shared mutex for some thread operations */
287 mutable SharedMutex thread_mutex_;
288 /*! \brief Pointer to the stl thread object */
289 std::atomic<std::thread *> thread_;
290 /*! \brief Signaled when the thread is started and ready to execute user code */
291 std::shared_ptr<ManualEvent> ready_event_;
292 /*! \brief Thread will block after setting ready_event_ until start_event_ is signaled */
293 std::shared_ptr<ManualEvent> start_event_;
294 /*! \brief The ThreadGroup ownber managing this thread's lifecycle */
295 ThreadGroup *owner_;
296 /*! \brief Flag to determine if shutdown was requested. */
297 std::atomic<bool> shutdown_requested_;
298 /*!
299 * \brief Whether to automatically remove this thread's object from the ThreadGroup when the
300 * thread exists (perform its own cleanup)
301 */
302 std::atomic<bool> auto_remove_;
303 };
304
305 /*!
306 * \brief Constructor
307 */
308 inline ThreadGroup() : evEmpty_(std::make_shared<ManualEvent>()) {
309 evEmpty_->signal(); // Starts out empty
310 }
311
312 /*!
313 * \brief Destructor, perform cleanup. All child threads will be exited when this
314 * destructor completes
315 */
316 virtual ~ThreadGroup() {
317 request_shutdown_all();
318 join_all();
319 }
320
321 /*!
322 * \brief Check if the current thread a member if this ThreadGroup
323 * \return true if the current thread is a member of this thread group
324 * \note This lookup involved a linear search, so for a large number of threads,
325 * is it not advised to call this function in a performance-sensitive area
326 */
327 inline bool is_this_thread_in() const {
328 std::thread::id id = std::this_thread::get_id();
329 ReadLock guard(m_);
330 for (auto it = threads_.begin(), end = threads_.end(); it != end; ++it) {
331 std::shared_ptr<Thread> thrd = *it;
332 if (thrd->get_id() == id) {
333 return true;
334 }
335 }
336 return false;
337 }
338
339 /*!
340 * \brief Check if the current thread is a member of this ThreadGroup
341 * \param thrd The thread to search for
342 * \return true if the given thread is a member of this ThreadGroup
343 */
344 inline bool is_thread_in(std::shared_ptr<Thread> thrd) const {
345 if (thrd) {
346 std::thread::id id = thrd->get_id();
347 ReadLock guard(m_);
348 for (auto it = threads_.begin(), end = threads_.end(); it != end; ++it) {
349 std::shared_ptr<Thread> thrd = *it;
350 if (thrd->get_id() == id) {
351 return true;
352 }
353 }
354 return false;
355 } else {
356 return false;
357 }
358 }
359
360 /*!
361 * \brief Add a Thread object to this thread group
362 * \param thrd The thread to add to this ThreadGroup object
363 * \return true if the given thread was added to this ThreadGroup
364 */
365 inline bool add_thread(std::shared_ptr<Thread> thrd) {
366 if (thrd) {
367 WriteLock guard(m_);
368 auto iter = name_to_thread_.find(thrd->name());
369 if (iter == name_to_thread_.end()) {
370 name_to_thread_.emplace(std::make_pair(thrd->name(), thrd));
371 CHECK_EQ(threads_.insert(thrd).second, true);
372 evEmpty_->reset();
373 return true;
374 }
375 }
376 return false;
377 }
378
379 /*!
380 * \brief Remove a Thread object from this thread group
381 * \param thrd The thread to remove from this ThreadGroup object
382 * \return true if the given thread was removed from this ThreadGroup
383 */
384 inline bool remove_thread(std::shared_ptr<Thread> thrd) {
385 if (thrd) {
386 WriteLock guard(m_);
387 auto iter = threads_.find(thrd);
388 if (iter != threads_.end()) {
389 name_to_thread_.erase(thrd->name());
390 threads_.erase(iter);
391 if (threads_.empty()) {
392 evEmpty_->signal();
393 }
394 return true;
395 }
396 }
397 return false;
398 }
399
400 /*!
401 * \brief Join all threads in this ThreadGroup
402 * \note While it is not valid to call 'join' on an auto-remove thread, this function will
403 * wait for auto-remove threads to exit (waits for the ThreadGroup to become empty)
404 */
405 inline void join_all() {
406 CHECK_EQ(!is_this_thread_in(), true);
407 do {
408 std::unique_lock<std::mutex> lk(join_all_mtx_);
409 std::unordered_set<std::shared_ptr<Thread>> working_set;
410 {
411 ReadLock guard(m_);
412 for (auto iter = threads_.begin(), e_iter = threads_.end(); iter != e_iter; ++iter) {
413 if (!(*iter)->is_auto_remove()) {
414 working_set.emplace(*iter);
415 }
416 }
417 }
418 // Where possible, prefer to do a proper join rather than simply waiting for empty
419 // (easier to troubleshoot)
420 while (!working_set.empty()) {
421 std::shared_ptr<Thread> thrd;
422 thrd = *working_set.begin();
423 if (thrd->joinable()) {
424 thrd->join();
425 }
426 remove_thread(thrd);
427 working_set.erase(working_set.begin());
428 thrd.reset();
429 }
430 // Wait for auto-remove threads (if any) to complete
431 } while (0);
432 evEmpty_->wait();
433 CHECK_EQ(threads_.size(), 0);
434 }
435
436 /*!
437 * \brief Call request_shutdown() on all threads in this ThreadGroup
438 * \param make_all_joinable If true, remove all auto_remove flags from child threads
439 */
440 inline void request_shutdown_all(const bool make_all_joinable = true) {
441 std::unique_lock<std::mutex> lk(join_all_mtx_);
442 ReadLock guard(m_);
443 for (auto &thread : threads_) {
444 if (make_all_joinable) {
445 thread->make_joinable();
446 }
447 thread->request_shutdown();
448 }
449 }
450
451 /*!
452 * \brief Return the number of threads in this thread group
453 * \return Number of threads in this thread group
454 */
455 inline size_t size() const {
456 ReadLock guard(m_);
457 return threads_.size();
458 }
459
460 /*!
461 * \brief Check if the ThreadGroup is empty
462 * \return true if the ThreadGroup is empty
463 */
464 inline bool empty() const {
465 ReadLock guard(m_);
466 return threads_.size() == 0;
467 }
468
469 /*!
470 * \brief Create and launch a new Thread object which will be owned by this ThreadGroup
471 * \tparam StartFunction Function type for the thread 'main' function
472 * \tparam ThreadType managedThreadclass type (in case it's derived, for instance)
473 * \tparam Args Arguments to pass to the thread 'main' function
474 * \param threadName Name if the thread. Must be unique for a ThreadGroup object
475 * \param auto_remove If true, automatically remove this Thread object from the
476 * ThreadGroup owner upon exit
477 * \param start_function The Thread's 'main' function
478 * \param args Arguments to pass to the Thread's 'main' function
479 * \return true if the thread was successfully created and added to the ThreadGroup
480 * If false is returned, the thread may have already been started, but if something
481 * went wrong (ie duplicte thread name for the ThreadGroup), then request_shutdown()
482 * will have been been called on the running thread
483 */
484 template <typename StartFunction, typename ThreadType = Thread, typename... Args>
485 inline bool create(
486 const std::string &threadName, bool auto_remove, StartFunction start_function, Args... args) {
487 typename ThreadType::SharedPtr newThread(new ThreadType(threadName, this));
488 return Thread::launch(newThread, auto_remove, start_function, args...);
489 }
490
491 /*!
492 * \brief Lookup Thread object by name
493 * \param name Name of the thread to look up
494 * \return A shared pointer to the Thread object
495 */
496 inline std::shared_ptr<Thread> thread_by_name(const std::string &name) {
497 ReadLock guard(m_);
498 auto iter = name_to_thread_.find(name);
499 if (iter != name_to_thread_.end()) {
500 return iter->second;
501 }
502 return nullptr;
503 }
504
505 private:
506 /*! \brief ThreadGroup synchronization mutex */
507 mutable SharedMutex m_;
508 /*! \brief join_all/auto_remove synchronization mutex */
509 mutable std::mutex join_all_mtx_;
510 /*! \brief Set of threads owned and managed by this ThreadGroup object */
511 std::unordered_set<std::shared_ptr<Thread>> threads_;
512 /*! \brief Manual event which is signaled when the thread group is empty */
513 std::shared_ptr<ManualEvent> evEmpty_;
514 /*! \brief name->thread mapping */
515 std::unordered_map<std::string, std::shared_ptr<Thread>> name_to_thread_;
516 };
517
518 /*!
519 * \brief Blocking queue thread class
520 * \tparam ObjectType Object type to queue
521 * \tparam quit_item Object value to signify queue shutdown (ie nullptr for pointer type is common)
522 * \note See gtest unit test Syc.ManagedThreadLaunchQueueThread for a usage example
523 */
524 template <typename ObjectType, ObjectType quit_item>
525 class BlockingQueueThread : public ThreadGroup::Thread {
526 using BQT = BlockingQueueThread<ObjectType, quit_item>;
527
528 public:
529 /*!
530 * \brief Constructor
531 * \param name Name for the blockin g queue thread. Must be unique for a specific ThreadGroup
532 * \param owner ThreadGroup lifecycle manafger/owner
533 * \param thrd Optionally attach an existing stl thread object
534 */
535 BlockingQueueThread(
536 const std::string &name, dmlc::ThreadGroup *owner, std::thread *thrd = nullptr)
537 : ThreadGroup::Thread(name, owner, thrd), shutdown_in_progress_(false) {}
538
539 /*!
540 * \brief Destructor
541 */
542 ~BlockingQueueThread() override {
543 // Call to parent first because we don't want to wait for the queue to empty
544 ThreadGroup::Thread::request_shutdown();
545 request_shutdown();
546 }
547
548 /*!
549 * \brief Signal the thread that a shutdown is desired
550 * \note Since consumer doesn't necessarily get items in order, we must wait for
551 * the queue to empty.
552 * This is generally a shutdown procedure and should not be called from
553 * a performance-sensitive area
554 */
555 void request_shutdown() override {
556 shutdown_in_progress_ = true;
557 while (queue_->size_approx() > 0 && !ThreadGroup::Thread::is_shutdown_requested()) {
558 std::this_thread::sleep_for(std::chrono::milliseconds(1));
559 }
560 ThreadGroup::Thread::request_shutdown();
561 queue_->enqueue(quit_item);
562 }
563
564 /*!
565 * \brief Enqueue and item
566 * \param item The item to enqueue
567 */
568 void enqueue(const ObjectType &item) {
569 if (!shutdown_in_progress_) {
570 queue_->enqueue(item);
571 }
572 }
573
574 /*!
575 * \brief Get the approximate size of the queue
576 * \return The approximate size of the queue
577 */
578 size_t size_approx() const {
579 return queue_->size_approx();
580 }
581
582 /*!
583 * \brief Launch to the 'run' function which will, in turn, call the class'
584 * 'run' function, passing it the given 'secondary_function'
585 * for it to call as needed
586 * \tparam SecondaryFunction Type of the secondary function for 'run' override
587 * to call as needed
588 * \param pThis Pointer to the managed thread to launch
589 * \param secondary_function secondary function for 'run' override to call as needed
590 * \return true if thread is launched successfully and added to the ThreadGroup
591 */
592 template <typename SecondaryFunction>
593 static bool launch_run(std::shared_ptr<BQT> pThis, SecondaryFunction secondary_function) {
594 return ThreadGroup::Thread::launch(
595 pThis, true,
596 [](std::shared_ptr<BQT> pThis, SecondaryFunction secondary_function) {
597 return pThis->run(secondary_function);
598 },
599 pThis, secondary_function);
600 }
601
602 /*!
603 * \brief Thread's main queue processing function
604 * \tparam OnItemFunction Function type to call when an item is dequeued
605 * \param on_item_function Function to call when an item is dequeued
606 * \return 0 if completed through a `quit_item`, nonzero if on_item_function requested an exit
607 */
608 template <typename OnItemFunction>
609 inline int run(OnItemFunction on_item_function) {
610 int rc = 0;
611 do {
612 ObjectType item;
613 queue_->wait_dequeue(item);
614 if (item == quit_item) {
615 break;
616 }
617 rc = on_item_function(item);
618 if (rc) {
619 break;
620 }
621 } while (true);
622 return rc;
623 }
624
625 private:
626 /*! \brief The blocking queue associated with this thread */
627 std::shared_ptr<dmlc::moodycamel::BlockingConcurrentQueue<ObjectType>> queue_
628 = std::make_shared<dmlc::moodycamel::BlockingConcurrentQueue<ObjectType>>();
629 /*! \brief Whether shutdown request is in progress */
630 std::atomic<bool> shutdown_in_progress_;
631 };
632
633 /*!
634 * \brief Managed timer thread
635 * \tparam Duration Duration type (ie seconds, microseconds, etc)
636 */
637 template <typename Duration>
638 class TimerThread : public ThreadGroup::Thread {
639 using ThreadGroup::Thread::is_shutdown_requested;
640
641 public:
642 /*!
643 * \brief Constructor
644 * \param name Name of the timer thread
645 * \param owner ThreadGroup owner if the timer thread
646 */
647 TimerThread(const std::string &name, ThreadGroup *owner) : Thread(name, owner) {}
648
649 /*!
650 * \brief Destructor
651 */
652 ~TimerThread() override {
653 request_shutdown();
654 }
655
656 /*!
657 * \brief Launch to the 'run' function which will, in turn, call the class'
658 * 'run' function, passing it the given 'secondary_function'
659 * for it to call as needed
660 * \tparam SecondaryFunction Type of the secondary function for 'run' override
661 * to call as needed
662 * \param pThis Pointer to the managed thread to launch
663 * \param secondary_function secondary function for 'run' override to call as needed
664 * \return true if thread is launched successfully and added to the ThreadGroup
665 */
666 template <typename SecondaryFunction>
667 static bool launch_run(
668 std::shared_ptr<TimerThread<Duration>> pThis, SecondaryFunction secondary_function) {
669 return ThreadGroup::Thread::launch(
670 pThis, true,
671 [](std::shared_ptr<TimerThread<Duration>> pThis, SecondaryFunction secondary_function) {
672 return pThis->run(secondary_function);
673 },
674 pThis, secondary_function);
675 }
676
677 /*!
678 * \brief Start a given timer thread
679 * \tparam Function Type of the timer function
680 * \param timer_thread Thread object to perform the timer events
681 * \param duration Duration between the end end of the timer function and the next timer event
682 * \param function Function to call when the timer expires
683 * \note Calling shutdown_requested() will cause the thread to exit the next time that the timer
684 * expires.
685 */
686 template <typename Function>
687 static void start(
688 std::shared_ptr<TimerThread> timer_thread, Duration duration, Function function) {
689 timer_thread->duration_ = duration;
690 launch_run(timer_thread, function);
691 }
692
693 /*!
694 * \brief Internal timer execution function
695 * \tparam OnTimerFunction Type of function to call each time the timer expires
696 * \param on_timer_function Function to call each time the timer expires
697 * \return Exit code of the thread
698 */
699 template <typename OnTimerFunction>
700 inline int run(OnTimerFunction on_timer_function) {
701 int rc = 0;
702 while (!is_shutdown_requested()) {
703 std::this_thread::sleep_for(duration_);
704 if (!is_shutdown_requested()) {
705 rc = on_timer_function();
706 }
707 }
708 return rc;
709 }
710
711 private:
712 Duration duration_;
713 };
714
715 /*
716 * Inline functions - see declarations for usage
717 */
718 template <typename StartFunction, typename... Args>
719 inline int ThreadGroup::Thread::entry_and_exit_f(
720 std::shared_ptr<Thread> pThis, StartFunction start_function, Args... args) {
721 int rc;
722 if (pThis) {
723 // Signal launcher that we're up and running
724 pThis->ready_event_->signal();
725 // Wait for launcher to be ready for us to start
726 pThis->start_event_->wait();
727 // Reset start_event_ for possible reuse
728 pThis->start_event_->reset(); // Reset in case it needs to be reused
729 // If we haven't been requested to shut down prematurely, then run the desired function
730 if (!pThis->is_shutdown_requested()) {
731 rc = start_function(args...);
732 } else {
733 rc = -1;
734 }
735 // If we're set up as auto-remove, then remove this thread from the thread group
736 if (pThis->is_auto_remove()) {
737 pThis->owner_->remove_thread(pThis);
738 }
739 // Release this thread shared pinter. May or may not be the last reference.
740 pThis.reset();
741 } else {
742 LOG(ERROR) << "Null pThis thread pointer";
743 rc = EINVAL;
744 }
745 return rc;
746 }
747
748 template <typename StartFunction, typename... Args>
749 inline bool ThreadGroup::Thread::launch(
750 std::shared_ptr<Thread> pThis, bool autoRemove, StartFunction start_function, Args... args) {
751 WriteLock guard(pThis->thread_mutex_);
752 CHECK_EQ(!pThis->thread_.load(), true);
753 CHECK_NOTNULL(pThis->owner_);
754 // Set auto remove
755 pThis->auto_remove_ = autoRemove;
756 // Create the actual stl thread object
757 pThis->thread_ = new std::thread(
758 Thread::template entry_and_exit_f<StartFunction, Args...>, pThis, start_function, args...);
759 // Attempt to add the thread to the thread group (after started, since in case
760 // something goes wrong, there's not a zombie thread in the thread group)
761 if (!pThis->owner_->add_thread(pThis)) {
762 pThis->request_shutdown();
763 LOG(ERROR) << "Duplicate thread name within the same thread group is not allowed";
764 }
765 // Wait for the thread to spin up
766 pThis->ready_event_->wait();
767 // Signal the thgread to continue (it will check its shutdown status)
768 pThis->start_event_->signal();
769 // Return if successful
770 return pThis->thread_.load() != nullptr;
771 }
772
773 /*!
774 * \brief Utility function to easily create a timer
775 * \tparam Duration Duration type (i.e. std::chrono::milliseconds)
776 * \tparam TimerFunction Function to call each time the timer expires
777 * \param timer_name Name of the timer. Must be unique per ThreadGroup object
778 * \param duration Duration of the timer between calls to timer_function
779 * \param owner ThreadGroup owner of the timer
780 * \param timer_function Function to call each time the timer expires
781 * \return true if the timer was successfully created
782 */
783 template <typename Duration, typename TimerFunction>
784 inline bool CreateTimer(const std::string &timer_name, const Duration &duration, ThreadGroup *owner,
785 TimerFunction timer_function) {
786 std::shared_ptr<dmlc::TimerThread<Duration>> timer_thread
787 = std::make_shared<dmlc::TimerThread<Duration>>(timer_name, owner);
788 dmlc::TimerThread<Duration>::start(timer_thread, duration, timer_function);
789 return timer_thread != nullptr;
790 }
791 } // namespace dmlc
792
793 #endif // DMLC_THREAD_GROUP_H_