Debian Codegraph @

3rdparty/xspublic/xscommon/xsens_threadpool.cpp

raw symbols SCIP
1
2 // Copyright (c) 2003-2019 Xsens Technologies B.V. or subsidiaries worldwide.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification,
6 // are permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice,
9 // this list of conditions, and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice,
12 // this list of conditions, and the following disclaimer in the documentation
13 // and/or other materials provided with the distribution.
14 //
15 // 3. Neither the names of the copyright holders nor the names of their contributors
16 // may be used to endorse or promote products derived from this software without
17 // specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
24 // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
26 // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
28 // SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
29 // OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
30 // ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
31 //
32
33 #include "xsens_threadpool.h"
34 #ifndef _MSC_VER
35 #include <unistd.h>
36 #include <cxxabi.h>
37 #endif
38 #ifdef XSENS_DEBUG
39 #include <typeinfo>
40 #endif
41
42 #include <vector>
43 #include <xstypes/xsexception.h>
44 #include "threading.h"
45 #include <atomic>
46
47 // Enable this if you want to disable multithreading
48 //#define ADD_TASK_EXECUTE_NOW
49
50 namespace xsens {
51 /////////////////////////////////////////////////////////////////////////////////////////
52 /////////////////////////////////////////////////////////////////////////////////////////
53 /////////////////////////////////////////////////////////////////////////////////////////
54
55 typedef std::map<unsigned int, std::shared_ptr<PooledTask>> TaskSet;
56 typedef std::set<PooledThread*> ThreadSet;
57 typedef std::vector<std::shared_ptr<PooledTask>> TaskList;
58
59 /*! \brief Returns the number of processor cores in the current system
60 */
61 int processorCount()
62 {
63 #if defined(_WIN32)
64 SYSTEM_INFO sysinfo;
65 ::GetSystemInfo( &sysinfo );
66 return (int) sysinfo.dwNumberOfProcessors;
67 #else
68 return sysconf(_SC_NPROCESSORS_ONLN);
69 // see http://stackoverflow.com/questions/150355/programmatically-find-the-number-of-cores-on-a-machine
70 // for OS-specific code
71 #endif
72 }
73
74 /////////////////////////////////////////////////////////////////////////////////////////
75 /////////////////////////////////////////////////////////////////////////////////////////
76 /////////////////////////////////////////////////////////////////////////////////////////
77
78 /*! \class ThreadPoolTask
79 \brief A generic task implementation for the thread pool
80 */
81
82 /*! \brief This function gets called by PooledThread when the exec() function returns false to determine if we should wait for a specific task
83 \details The default implementation returns 0 (no id to wait for)
84 \returns False to determine if we should wait for a specific task
85 */
86 unsigned int ThreadPoolTask::needToWaitFor()
87 {
88 return 0;
89 }
90
91 /////////////////////////////////////////////////////////////////////////////////////////
92 /////////////////////////////////////////////////////////////////////////////////////////
93 /////////////////////////////////////////////////////////////////////////////////////////
94
95 /*! \brief A class that contains a task and some administrative stuff
96 */
97 class PooledTask {
98 public:
99 ThreadPoolTask* m_task; //!< The task that is to be executed
100 unsigned int m_id; //!< The id that was assigned to the task by the ThreadPool
101 std::vector<std::shared_ptr<PooledTask>> m_dependentTasks; //!< A list of tasks that are waiting for this task to complete
102 XsThreadId m_threadId;
103 volatile std::atomic<bool> m_canceling;
104
105 PooledTask()
106 : m_task(nullptr)
107 , m_id(0)
108 , m_threadId(0)
109 , m_canceling(false)
110 , m_completed(false)
111 , m_completedMutex()
112 , m_completedCondition(m_completedMutex)
113 {
114 }
115
116 ~PooledTask()
117 {
118 signalCompleted();
119 delete m_task;
120 }
121
122 bool waitForCompletion(uint32_t timeout = UINT32_MAX)
123 {
124 Lock locker(&m_completedMutex);
125 if (!m_completed)
126 {
127 // This may look like a dead-lock situation with signalCompleted(), but it isn't
128 if (timeout == UINT32_MAX)
129 m_completedCondition.wait();
130 else
131 m_completedCondition.wait(timeout);
132 }
133 return m_completed;
134 }
135
136 void signalCompleted() noexcept
137 {
138 Lock locker(&m_completedMutex);
139 if (!m_completed)
140 {
141 m_completed = true;
142 locker.unlock();
143 m_completedCondition.broadcast();
144 }
145 }
146
147 private:
148 volatile std::atomic_bool m_completed;
149 Mutex m_completedMutex;
150 WaitCondition m_completedCondition;
151 };
152
153 /*! \brief Returns true if the task has been told to cancel itself */
154 bool ThreadPoolTask::isCanceling() const
155 {
156 if (m_container)
157 return m_container->m_canceling;
158 return false;
159 }
160
161 /*! \brief Returns the task ID of the task or 0 if it doesn't have a proper ID (yet) */
162 unsigned int ThreadPoolTask::taskId() const
163 {
164 if (m_container)
165 return m_container->m_id;
166 return 0;
167 }
168
169 /////////////////////////////////////////////////////////////////////////////////////////
170 /////////////////////////////////////////////////////////////////////////////////////////
171 /////////////////////////////////////////////////////////////////////////////////////////
172
173 /*! \brief A class that contains a thread that runs in a ThreadPool to execute tasks
174 \details These threads are created by the ThreadPool.
175 */
176 class PooledThread : public StandardThread
177 {
178 public:
179 PooledThread(ThreadPool* pool);
180 ~PooledThread();
181 bool isIdle() const;
182 bool isBusy() const;
183 unsigned int executedCount() const;
184 unsigned int completedCount() const;
185 unsigned int failedCount() const;
186
187 protected:
188 ThreadPool* m_pool; //!< The pool that contains this thread
189 std::shared_ptr<PooledTask> m_task; //!< The task that is currently being executed or NULL if the thread is idle
190 unsigned int m_executed; //!< The number of tasks that this thread has executed s o far, including incomplete tasks
191 unsigned int m_completed; //!< The number of tasks that this thread has completed so far, excluding incomplete tasks
192 unsigned int m_failed; //!< The number of tasks that this thread has failed to complete so far due to an exception
193
194 virtual int32_t innerFunction(void);
195 };
196
197 /*! \brief Constructor */
198 PooledThread::PooledThread(ThreadPool* pool)
199 : StandardThread()
200 , m_pool(pool)
201 , m_task(nullptr)
202 , m_executed(0)
203 , m_completed(0)
204 , m_failed(0)
205 {
206 }
207
208 /*! \brief Destructor */
209 PooledThread::~PooledThread()
210 {
211 stopThread();
212 m_pool = nullptr;
213 }
214
215 /*! \brief The inner function of the pooled thread.
216
217 The function will do tasks until the ThreadPool no longer supplies any tasks, at which point
218 it will return with a sleep time of 1ms.
219 */
220 int32_t PooledThread::innerFunction(void)
221 {
222 if (!m_task)
223 m_task = m_pool->getNextTask();
224
225 while (m_task && !isTerminating())
226 {
227 m_task->m_threadId = getThreadId();
228 bool complete = false;
229 try
230 {
231 if (m_task->m_task->exec())
232 {
233 ++m_completed;
234 complete = true;
235 }
236 else if (m_task->m_canceling)
237 {
238 ++m_failed;
239 complete = true;
240 }
241 }
242 #ifdef XSENS_DEBUG
243 catch (std::exception &e)
244 {
245 const std::type_info &et = typeid(e);
246 #ifdef __GNUC__
247 int status;
248 char *realname = abi::__cxa_demangle(et.name(), 0, 0, &status);
249 fprintf(stderr, "ThreadPool: Caught an unhandled %s(\"%s\")\n", realname, e.what());
250 free(realname);
251 #else
252 fprintf(stderr, "ThreadPool: Caught an unhandled %s: %s\n", et.name(), e.what());
253 #endif
254 complete = true;
255 }
256 #endif
257 catch(...)
258 {
259 #ifdef XSENS_DEBUG
260 fprintf(stderr, "ThreadPool: Caught an unhandled unknown exception\n");
261 #endif
262 m_task->m_task->onError();
263 ++m_failed;
264 complete = true;
265 }
266
267 ++m_executed;
268 if (complete)
269 m_pool->reportTaskComplete(m_task);
270 else
271 {
272 m_task->m_threadId = 0;
273 m_pool->reportTaskPaused(m_task);
274 }
275
276 m_task = m_pool->getNextTask();
277 }
278 return 1;
279 }
280
281 /*! \brief Return whether the thread is currently executing a task (false) or not (true)
282 */
283 bool PooledThread::isIdle() const
284 {
285 return (m_task == nullptr);
286 }
287
288 /*! \brief Return whether the thread is currently executing a task (true) or not (false)
289 */
290 bool PooledThread::isBusy() const
291 {
292 return !isIdle();
293 }
294
295 /*! \brief Return the number of tasks successfully or partially executed by the thread
296 */
297 unsigned int PooledThread::executedCount() const
298 {
299 return m_executed;
300 }
301
302 /*! \brief Return the number of tasks successfully executed by the thread
303 */
304 unsigned int PooledThread::completedCount() const
305 {
306 return m_completed;
307 }
308
309 /*! \brief Return the number of tasks that failed to execute properly
310 */
311 unsigned int PooledThread::failedCount() const
312 {
313 return m_failed;
314 }
315
316 /////////////////////////////////////////////////////////////////////////////////////////
317 /////////////////////////////////////////////////////////////////////////////////////////
318 /////////////////////////////////////////////////////////////////////////////////////////
319
320 /*! \class ThreadPool
321 \brief This class creates and maintains a number of threads that can execute finite-length tasks
322 \note See the test cases for examples on how to use the class
323 */
324
325 /*! \brief Construct a threadpool with a number of threads equal to the number of cores on the PC
326 */
327 ThreadPool::ThreadPool()
328 : m_nextId(1)
329 , m_suspended(false)
330 , m_terminating(false)
331 {
332 setPoolSize(0);
333 }
334
335 /*! \brief Destructor, clears any pending tasks and destroys the threads
336 */
337 ThreadPool::~ThreadPool()
338 {
339 m_terminating = true;
340 suspend(true);
341
342 // all threads should now be idle
343 m_tasks.clear();
344 m_tasksSearch.clear();
345 m_executing.clear();
346 m_delaying.clear();
347
348 try
349 {
350 for (ThreadSet::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
351 delete *it;
352 }
353 catch(...)
354 {
355 // nothing much we can do about this...
356 }
357 }
358
359 /*! \brief Add a task to be executed by the threadpool
360 \param task The task object whose exec() function will be called
361 \param afterId When not 0, the task will not be started until the task with the given id has completed
362
363 \returns The id of the task that was added or 0 if the task could not be added for some reason.
364 */
365 ThreadPool::TaskId ThreadPool::addTask(ThreadPoolTask* task, ThreadPool::TaskId afterId)
366 {
367 assert(!m_terminating);
368 std::shared_ptr<PooledTask> tmp(new PooledTask);
369 tmp->m_task = task;
370 Lock safety(&m_safe);
371 tmp->m_id = m_nextId;
372 task->m_container = tmp.get();
373
374 // determine next ID
375 if (!++m_nextId)
376 m_nextId = 1;
377
378 #ifndef ADD_TASK_EXECUTE_NOW
379 if (afterId)
380 {
381 std::shared_ptr<PooledTask> after = findTask(afterId);
382 if (after)
383 {
384 after->m_dependentTasks.push_back(tmp);
385 m_delaying[tmp->m_id] = tmp;
386 return tmp->m_id;
387 }
388 }
389
390 m_tasks.push_back(tmp);
391 m_tasksSearch[tmp->m_id] = tmp;
392 #else
393 task->exec();
394 task->signalCompleted();
395 #endif
396
397 return tmp->m_id;
398 }
399
400 /*! \brief Return the number of tasks that are currently in the queue or being executed
401 */
402 unsigned int ThreadPool::count()
403 {
404 Lock safety(&m_safe);
405 return (unsigned int) (m_tasks.size() + m_delaying.size() + m_executing.size());
406 }
407
408 /*! \brief Set the number of threads in the ThreadPool
409 \param poolsize When 0 or less two threads will be created for each processor core in the system (with a minimum of 4 threads), otherwise the desired number of threads will be created
410 */
411 void ThreadPool::setPoolSize(unsigned int poolsize)
412 {
413 if (poolsize == 0)
414 {
415 //int pc = processorCount();
416 //poolsize = ::std::max(4, pc*2);
417 poolsize = 12; // fixed count to prevent thread starvation on low-core PCs and overthreading on high-core PCs
418 }
419
420 bool wasSuspended = m_suspended;
421 suspend(poolsize < m_threads.size());
422 Lock safety(&m_safe);
423
424 // reduce size if pool is too large
425 if (poolsize < m_threads.size())
426 {
427 while (poolsize < m_threads.size())
428 {
429 delete *m_threads.begin();
430 m_threads.erase(m_threads.begin());
431 }
432 }
433
434 // increase size if pool is too small
435 for (unsigned int i = (unsigned int) m_threads.size(); i < poolsize; ++i)
436 {
437 PooledThread* t = new PooledThread(this);
438 m_threads.insert(t);
439 #ifdef XSENS_DEBUG
440 char bufje[64];
441 sprintf(bufje, "Pooled Thread %p", t);
442 #else
443 const char bufje[] = "Pooled Thread";
444 #endif
445 if (!t->startThread(bufje))
446 {
447 m_threads.erase(m_threads.find(t));
448 delete t;
449 throw XsException(XRV_ERROR, "Could not start thread for ThreadPool");
450 }
451 }
452
453 if (!wasSuspended)
454 resume();
455 }
456
457 /*! \brief Return the number of threads in the pool */
458 unsigned int ThreadPool::poolSize() const
459 {
460 return (unsigned int) m_threads.size();
461 }
462
463 /*! \brief Find a task with the supplied \a id
464 */
465 std::shared_ptr<PooledTask> ThreadPool::findTask(ThreadPool::TaskId id)
466 {
467 Lock safety(&m_safe);
468 TaskSet::iterator it = m_executing.find(id);
469 if (it != m_executing.end())
470 return it->second;
471
472 it = m_delaying.find(id);
473 if (it != m_delaying.end())
474 return it->second;
475
476 it = m_tasksSearch.find(id);
477 if (it != m_tasksSearch.end())
478 return it->second;
479
480 return std::shared_ptr<PooledTask>();
481 }
482
483 /*! \brief Find an XsThread with the specified \a id
484 */
485 XsThreadId ThreadPool::taskThreadId(TaskId id)
486 {
487 Lock safety(&m_safe);
488 TaskSet::iterator it = m_executing.find(id);
489 if (it != m_executing.end())
490 return it->second->m_threadId;
491 return 0;
492 }
493
494 /*! \brief Check if a task with the supplied \a id exists
495 */
496 bool ThreadPool::doesTaskExist(ThreadPool::TaskId id)
497 {
498 return findTask(id) != nullptr;
499 }
500
501 /*! \brief Remove the task with the supplied \a id if it exists, waits for the task to be finished
502 */
503 void ThreadPool::cancelTask(ThreadPool::TaskId id, bool wait)
504 {
505 Lock safety(&m_safe);
506 TaskSet::iterator it = m_executing.find(id);
507 if (it != m_executing.end())
508 {
509 it->second->m_canceling = true;
510 safety.unlock();
511 if (wait)
512 waitForCompletion(id);
513 return;
514 }
515
516 it = m_delaying.find(id);
517 if (it != m_delaying.end())
518 m_delaying.erase(it);
519
520 it = m_tasksSearch.find(id);
521 if (it != m_tasksSearch.end())
522 m_tasksSearch.erase(it);
523 }
524
525 /*! \brief Wait for the task with the given ID to complete
526 */
527 void ThreadPool::waitForCompletion(ThreadPool::TaskId id)
528 {
529 std::shared_ptr<PooledTask> task = findTask(id);
530 if (task != nullptr)
531 task->waitForCompletion();
532 }
533
534 /*! \brief Called by PooledThread to notify the ThreadPool that a task was completed
535 \note After this call, the supplied \a task is invalid
536 */
537 void ThreadPool::reportTaskComplete(std::shared_ptr<PooledTask> task)
538 {
539 Lock safety(&m_safe);
540
541 // remove task from 'executing' list
542 TaskSet::iterator it = m_executing.find(task->m_id);
543 if (it != m_executing.end())
544 m_executing.erase(it);
545
546 // notify dependent tasks that their dependency has been fulfilled
547 for (TaskList::iterator dep = task->m_dependentTasks.begin(); dep != task->m_dependentTasks.end(); ++dep)
548 {
549 it = m_delaying.find((*dep)->m_id);
550 if (it != m_delaying.end())
551 {
552 m_tasks.push_back(it->second);
553 m_tasksSearch[it->second->m_id] = it->second;
554 m_delaying.erase(it);
555 }
556 }
557 task->signalCompleted();
558 }
559
560 /*! \brief Return the next task that should be run and mark it as executing
561 */
562 std::shared_ptr<PooledTask> ThreadPool::getNextTask()
563 {
564 Lock safety(&m_safe);
565 if (!m_suspended && !m_tasks.empty())
566 {
567 std::shared_ptr<PooledTask> tmp = m_tasks.front();
568 m_tasks.pop_front();
569 m_tasksSearch.erase(tmp->m_id);
570 m_executing[tmp->m_id] = tmp;
571 return tmp;
572 }
573
574 return std::shared_ptr<PooledTask>();
575 }
576
577 /*! \brief Called by PooledThread to notify the ThreadPool that its running task has to wait for something
578 \details This function can be called when the task failed to run to completion. It will be rescheduled
579 at the end of the queue and its exec function will be called again.
580 To notify the threadpool, a task should return 'false' from its exec() function.
581 \param task The task that is to be paused
582 \note The task itself is responsible for maintaining its state between the exec calls
583 \note After calling this function the PooledThread should consider the supplied \a task as invalid since it's possible that it has been picked up, executed and deleted by another thread during the function return
584 */
585 void ThreadPool::reportTaskPaused(std::shared_ptr<PooledTask> task)
586 {
587 Lock safety(&m_safe);
588
589 // remove task from 'executing' list
590 TaskSet::iterator it = m_executing.find(task->m_id);
591 if (it != m_executing.end())
592 m_executing.erase(it);
593
594 // add task back into either the delaying list if it should wait for something
595 unsigned int waitForId = task->m_task->needToWaitFor();
596 if (waitForId)
597 {
598 std::shared_ptr<PooledTask> after = findTask(waitForId);
599 if (after)
600 {
601 after->m_dependentTasks.push_back(task);
602 m_delaying[task->m_id] = task;
603 return;
604 }
605 }
606
607 // add task into ready queue
608 m_tasks.push_back(task);
609 m_tasksSearch[task->m_id] = task;
610 }
611
612 /*! \brief Suspend execution of tasks, any currently executing tasks will run to completion,
613 but queued tasks will not be started.
614 \param wait When set to true the function waits for all threads to finish their current task
615 \sa resume
616 */
617 void ThreadPool::suspend(bool wait) noexcept
618 {
619 Lock safety(&m_safe);
620 m_suspended = true;
621
622 if (wait)
623 {
624 safety.unlock();
625
626 for (ThreadSet::const_iterator it = m_threads.begin(); it != m_threads.end(); ++it)
627 while ((*it)->isBusy())
628 xsYield();
629 }
630 }
631
632 /*! \brief Resume execution of tasks.
633 \sa suspend
634 */
635 void ThreadPool::resume()
636 {
637 Lock safety(&m_safe);
638 m_suspended = false;
639 }
640
641 /*! \brief Return the number of tasks executed (including paused) by the given thread
642 */
643 unsigned int ThreadPool::executedCount(unsigned int thread) const
644 {
645 unsigned int i = 0;
646 for (ThreadSet::const_iterator it = m_threads.begin(); it != m_threads.end(); ++it, ++i)
647 if (i == thread)
648 return (*it)->executedCount();
649 return 0;
650 }
651
652 /*! \brief Return the number of tasks completed by the given thread
653 */
654 unsigned int ThreadPool::completedCount(unsigned int thread) const
655 {
656 unsigned int i = 0;
657 for (ThreadSet::const_iterator it = m_threads.begin(); it != m_threads.end(); ++it, ++i)
658 if (i == thread)
659 return (*it)->completedCount();
660 return 0;
661 }
662
663 /*! \brief Return the number of tasks that failed to execute in the given thread
664 */
665 unsigned int ThreadPool::failedCount(unsigned int thread) const
666 {
667 unsigned int i = 0;
668 for (ThreadSet::const_iterator it = m_threads.begin(); it != m_threads.end(); ++it, ++i)
669 if (i == thread)
670 return (*it)->failedCount();
671 return 0;
672 }
673
674 ThreadPool* gPool = NULL;
675 bool gManagePool = true;
676
677 /*! \brief Return the global thread pool object, it will be created if it did not yet exist */
678 ThreadPool* ThreadPool::instance()
679 {
680 if (gPool)
681 return gPool;
682 gPool = new ThreadPool;
683 gManagePool = true;
684 return gPool;
685 }
686
687 /*! \brief Destroy the global thread pool object
688 \details If the pool was not created by this library, the current library will only stop using
689 the pool, but will leave the object intact.
690 The next call to instance() will create a new pool.
691 \sa instance
692 */
693 void ThreadPool::destroy()
694 {
695 if (gPool && gManagePool)
696 delete gPool;
697 gPool = NULL;
698 gManagePool = true;
699 }
700
701 /*! \brief Set the threadpool to use
702 \details This function allows the user to supply his own ThreadPool object to be used
703 by all subsequent operations. If another pool was created by this library, it will be
704 destroyed.
705 \param pool The new threadpool object to use. If NULL is supplied, it is simply destroyed
706 or stopped from being used.
707 \sa destroy
708 */
709 void ThreadPool::setPool(ThreadPool* pool)
710 {
711 if (pool != gPool)
712 {
713 destroy();
714 if (pool)
715 {
716 gPool = pool;
717 gManagePool = false;
718 }
719 }
720 }
721
722 /////////////////////////////////////////////////////////////////////////////////////////
723 /////////////////////////////////////////////////////////////////////////////////////////
724 /////////////////////////////////////////////////////////////////////////////////////////
725
726 /*! \class TaskCompletionWaiter
727 \brief A class that allows multiple-dependency waiting
728 \details A normal task in the ThreadPool can only wait for one task ID. This class allows waiting
729 for multiple IDs. The IDs to wait for can be supplied upon creation or added later, but they
730 should NOT be added once the object has been scheduled.
731 The TaskCompletionWaiter must be scheduled in the ThreadPool that contains the task IDs to wait
732 for so it can do its job.
733
734 \note If you want a thread outside the ThreadPool to wait for multiple tasks to complete, create a
735 TaskCompletionWaiter, schedule it and wait for the TaskCompletionWaiter to complete through
736 the ThreadPool::waitForCompletion function.
737 */
738
739 /*! \brief Constructor, sets up an empty waiter */
740 TaskCompletionWaiter::TaskCompletionWaiter(ThreadPool* pool)
741 : ThreadPoolTask()
742 , m_pool(pool)
743 {}
744
745 /*! \brief Constructor, sets up a waiter that waits for all items in the list to be completed */
746 TaskCompletionWaiter::TaskCompletionWaiter(const std::list<unsigned int>& waitlist, ThreadPool* pool)
747 : ThreadPoolTask()
748 , m_pool(pool)
749 , m_waitList(waitlist)
750 {}
751
752 /*! \brief Destructor */
753 TaskCompletionWaiter::~TaskCompletionWaiter()
754 {}
755
756 /*! \brief task function, checks if there are tasks left that we should be waiting for
757 \details The function returns false if at least one of the wait tasks still exists
758 \returns True if successfully executed
759 */
760 bool TaskCompletionWaiter::exec()
761 {
762 while (m_waitList.size())
763 {
764 // if the task exists, reschedule this task to recheck after the task completes
765 if (m_pool->doesTaskExist(*m_waitList.begin()))
766 return false;
767
768 m_waitList.erase(m_waitList.begin());
769 }
770 return true;
771 }
772
773 /*! \brief If there are wait tasks left, this function will return the id of the first in the list
774 \returns The id of the first task in the list
775 */
776 unsigned int TaskCompletionWaiter::needToWaitFor()
777 {
778 if (m_waitList.size())
779 return *m_waitList.begin();
780 return 0;
781 }
782
783 /*! \brief Add the id of a task to wiat for to the list.
784 \param id The ID to add
785 \note This function should NOT be called once the task has been scheduled!
786 */
787 void TaskCompletionWaiter::addWaitId(unsigned int id)
788 {
789 m_waitList.push_back(id);
790 }
791 } // namespace xsens