Debian Codegraph @

3rdparty/xspublic/xscommon/xsens_mutex.h

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 #ifndef XSENS_MUTEX_H
34 #define XSENS_MUTEX_H
35
36 #include <cstdint>
37 #include <atomic>
38 #include <xstypes/xsthread.h>
39 #include <xstypes/xstimestamp.h>
40
41 #include <deque>
42
43 #ifndef __GNUC__
44 #pragma warning(disable: 4127)
45 #endif
46
47 namespace xsens {
48 class Lock;
49 class LockReadWrite;
50 class LockSuspendable;
51 class WaitCondition;
52 enum LockState { LS_Unlocked, LS_Read, LS_Write, LS_SuspendedWrite };
53
54 /*! \class Mutex
55 \brief A base mutex class
56 */
57 class Mutex {
58 private:
59 #if !XSENS_USE_POSIX_LOCKING
60 CRITICAL_SECTION m_mutex;
61 #else
62 pthread_mutexattr_t m_attr;
63 pthread_mutex_t m_mutex;
64 #endif
65 XsThreadId m_lockedBy;
66 volatile std::atomic_int m_lockCount;
67 friend class Lock;
68 friend class WaitCondition;
69 public:
70 Mutex()
71 : m_lockedBy(0)
72 , m_lockCount(0)
73 {
74 #if !XSENS_USE_POSIX_LOCKING
75 ::InitializeCriticalSection(&m_mutex);
76 #else
77 // this is required to get the same behaviour we have in windows
78 pthread_mutexattr_init(&m_attr);
79 pthread_mutexattr_settype(&m_attr, PTHREAD_MUTEX_RECURSIVE);
80 pthread_mutex_init(&m_mutex, &m_attr);
81 #endif
82 }
83 ~Mutex()
84 {
85 assert(m_lockCount == 0);
86 assert(m_lockedBy == 0);
87 #if !XSENS_USE_POSIX_LOCKING
88 ::DeleteCriticalSection(&m_mutex);
89 #else
90 pthread_mutex_destroy(&m_mutex);
91 pthread_mutexattr_destroy(&m_attr);
92 #endif
93 }
94 Mutex(Mutex const&) = delete;
95 Mutex& operator=(Mutex const&) = delete;
96 Mutex(Mutex &&) = delete;
97 Mutex& operator=(Mutex &&) = delete;
98
99 /*! \brief Claims (locks) a mutex
100 \returns True if successful
101 */
102 inline bool claimMutex()
103 {
104 #if !XSENS_USE_POSIX_LOCKING
105 ::EnterCriticalSection(&m_mutex);
106 #else
107 pthread_mutex_lock(&m_mutex);
108 #endif
109 ++m_lockCount;
110 m_lockedBy = xsGetCurrentThreadId();
111 return true;
112 }
113
114 /*! \brief Releases (unlocks) a mutex
115 \returns True if successful
116 */
117 inline bool releaseMutex()
118 {
119 if (!--m_lockCount)
120 m_lockedBy = 0;
121 #if !XSENS_USE_POSIX_LOCKING
122 ::LeaveCriticalSection(&m_mutex);
123 #else
124 pthread_mutex_unlock(&m_mutex);
125 #endif
126 return true;
127 }
128
129 /*! \brief Tries to claim (lock) a mutex
130 \returns True if successful
131 */
132 inline bool tryClaimMutex()
133 {
134 // *CriticalSection returns true on success, pthread_* returns 0 on success.
135 #if !XSENS_USE_POSIX_LOCKING
136 if (::TryEnterCriticalSection(&m_mutex))
137 #else
138 if (pthread_mutex_trylock(&m_mutex) == 0)
139 #endif
140 {
141 ++m_lockCount;
142 m_lockedBy = xsGetCurrentThreadId();
143 return true;
144 }
145 return false;
146 }
147 #ifdef XSENS_DEBUG
148 // this function is only intended as a debug function for use in assert statements
149 inline bool haveLock() const
150 {
151 return m_lockedBy == xsGetCurrentThreadId();
152 }
153 #endif
154
155 /*! \returns True if a mutex is locked
156 */
157 inline bool isLocked() const volatile
158 {
159 return m_lockCount > 0;
160 }
161 };
162
163
164 /*! \class MutexReadWrite
165 \brief A readers-writer mutex class.
166 \details Any number of readers can claim the mutex at the same time, which blocks a writer from
167 claiming it. If a writer claims the mutex, all subsequent read claims will be blocked until
168 no more read claims exist and the write claim has been completed (released). Recursive read claims
169 within a thread that already has a read or write claim for this mutex will be granted to prevent
170 deadlocks.
171 */
172 class MutexReadWrite {
173 private:
174 Mutex m_access;
175 volatile std::atomic_int m_writeRef;
176 volatile std::atomic<XsThreadId> m_writeLocked;
177 volatile std::atomic_int m_writeLocksPending;
178 XsThreadId* m_readLocked;
179
180 int m_readLockMax;
181 int m_readLockCount;
182 friend class LockReadWrite;
183 MutexReadWrite(MutexReadWrite const&) = delete;
184 MutexReadWrite& operator=(MutexReadWrite const&) = delete;
185 MutexReadWrite(MutexReadWrite &&) = delete;
186 MutexReadWrite& operator=(MutexReadWrite &&) = delete;
187
188 public:
189 inline MutexReadWrite()
190 : m_writeRef(0)
191 , m_writeLocked(0)
192 , m_writeLocksPending(0)
193 {
194 m_readLockMax = 32;
195 m_readLocked = new XsThreadId[m_readLockMax];
196 m_readLockCount = 0;
197 }
198 inline ~MutexReadWrite()
199 {
200 delete[] m_readLocked;
201 }
202 private:
203 inline void addReadLock(XsThreadId cid)
204 {
205 if (m_readLockCount == m_readLockMax)
206 {
207 m_readLockMax = m_readLockMax*2;
208 XsThreadId* tmp = new XsThreadId[m_readLockMax];
209 memcpy(tmp, m_readLocked, ((unsigned int) m_readLockCount)*sizeof(XsThreadId));
210 delete[] m_readLocked;
211 m_readLocked = tmp;
212 }
213 m_readLocked[m_readLockCount++] = cid;
214 }
215
216 inline void enterAtomic()
217 {
218 m_access.claimMutex();
219 }
220
221 inline void leaveAtomic()
222 {
223 m_access.releaseMutex();
224 }
225
226 inline bool claimMutex(bool write)
227 {
228 XsThreadId cid = xsGetCurrentThreadId();
229 // write lock
230 if (write)
231 {
232 enterAtomic();
233 ++m_writeLocksPending;
234 while(1)
235 {
236 bool readFail = false;
237 if (m_writeLocked == 0)
238 {
239 for (int i = 0; i < m_readLockCount; ++i)
240 {
241 if (m_readLocked[i] != cid)
242 {
243 readFail = true;
244 break;
245 }
246 }
247 }
248
249 if (m_writeLocked != cid && (m_writeLocked != 0 || readFail))
250 {
251 leaveAtomic();
252 xsYield(); // wait for other locks to end
253 enterAtomic();
254 }
255 else
256 {
257 ++m_writeRef;
258 --m_writeLocksPending;
259 m_writeLocked = cid;
260 leaveAtomic();
261 return true;
262 }
263 }
264 }
265 // read lock
266 else
267 while(1)
268 {
269 enterAtomic();
270 bool readGot = false;
271 if ((m_writeLocked == 0 && m_writeLocksPending == 0) || m_writeLocked == cid)
272 readGot = true;
273 else
274 for (int i = 0; i < m_readLockCount; ++i)
275 if (m_readLocked[i] == cid)
276 {
277 readGot = true;
278 break;
279 }
280
281 if (readGot)
282 {
283 addReadLock(cid);
284 leaveAtomic();
285 return true;
286 }
287 leaveAtomic();
288 // wait for write lock to end
289 xsYield();
290 }
291 }
292
293 /*! \brief Downgrade an existing write lock to a read lock */
294 inline bool downgradeToRead()
295 {
296 XsThreadId cid = xsGetCurrentThreadId();
297 enterAtomic();
298 if (m_writeLocked == cid)
299 {
300 if (--m_writeRef == 0)
301 m_writeLocked = 0;
302 addReadLock(cid);
303 leaveAtomic();
304 return true;
305 }
306 leaveAtomic();
307 return false;
308 }
309
310 inline bool releaseMutex(bool write)
311 {
312 XsThreadId cid = xsGetCurrentThreadId();
313 enterAtomic();
314 if (write)
315 {
316 if (m_writeLocked == cid)
317 {
318 if (--m_writeRef == 0)
319 m_writeLocked = 0;
320 }
321 else
322 {
323 leaveAtomic();
324 return false;
325 }
326 }
327 else
328 {
329 if (m_readLockCount == 0)
330 {
331 leaveAtomic();
332 return false;
333 }
334 for (int i = m_readLockCount-1; i >= 0; --i)
335 if (m_readLocked[i] == cid)
336 {
337 for (int j = i+1; j < m_readLockCount; ++j)
338 m_readLocked[j-1] = m_readLocked[j];
339 --m_readLockCount;
340 break;
341 }
342 }
343 leaveAtomic();
344 return true;
345 }
346
347 inline bool tryClaimMutex(bool write, uint32_t timeout)
348 {
349 XsThreadId cid = xsGetCurrentThreadId();
350 long long timeToEnd = XsTimeStamp_now(0) + timeout;
351
352 // write lock
353 if (write)
354 {
355 enterAtomic();
356 ++m_writeLocksPending;
357 leaveAtomic();
358 do
359 {
360 enterAtomic();
361 bool readFail = false;
362 if (m_writeLocked == 0)
363 {
364 for (int i = 0; i < m_readLockCount; ++i)
365 if (m_readLocked[i] != cid)
366 {
367 readFail = true;
368 break;
369 }
370 }
371
372 if (m_writeLocked != cid && (m_writeLocked != 0 || readFail))
373 {
374 leaveAtomic();
375 // wait for other locks to end
376 xsYield();
377 }
378 else
379 {
380 ++m_writeRef;
381 --m_writeLocksPending;
382 m_writeLocked = cid;
383 leaveAtomic();
384 return true;
385 }
386 } while(XsTimeStamp_now(0) >= timeToEnd);
387 enterAtomic();
388 --m_writeLocksPending;
389 leaveAtomic();
390 return false;
391 }
392 // read lock
393 // else
394 do {
395 enterAtomic();
396
397 bool readGot = false;
398 if ((m_writeLocked == 0 && m_writeLocksPending == 0) || m_writeLocked == cid)
399 readGot = true;
400 else
401 {
402 for (int i = 0; i < m_readLockCount; ++i)
403 if (m_readLocked[i] == cid)
404 {
405 readGot = true;
406 break;
407 }
408 }
409
410 if (readGot)
411 {
412 addReadLock(cid);
413 leaveAtomic();
414 return true;
415 }
416 leaveAtomic();
417 // wait for write lock to end
418 xsYield();
419 } while (XsTimeStamp_now(0) <= timeToEnd);
420 return false;
421 }
422
423 #ifdef XSENS_DEBUG
424 public: // these functions should only be used internally and in assert statements
425 #endif
426 inline bool haveWriteClaim() const
427 {
428 bool rv = false;
429 XsThreadId cid = xsGetCurrentThreadId();
430
431 const_cast<MutexReadWrite*>(this)->enterAtomic();
432 if (m_writeLocked == cid)
433 rv = true;
434 const_cast<MutexReadWrite*>(this)->leaveAtomic();
435 return rv;
436 }
437 // this function is only intended as a debug function for use in assert statements
438 inline bool haveReadClaim() const
439 {
440 bool rv = false;
441 XsThreadId cid = xsGetCurrentThreadId();
442
443 const_cast<MutexReadWrite*>(this)->enterAtomic();
444 if (m_writeLocked == cid)
445 rv = true;
446 else
447 {
448 for (int i = 0; i < m_readLockCount; ++i)
449 if (m_readLocked[i] == cid)
450 {
451 rv = true;
452 break;
453 }
454 }
455 const_cast<MutexReadWrite*>(this)->leaveAtomic();
456 return rv;
457 }
458 };
459
460 /*! \brief An enum that hold mutex status flags
461 */
462 enum MutexStatusFlags : int {
463 MSF_HaveReadLock = 1,
464 MSF_HaveWriteLock = 2,
465 MSF_WriteLockSuspended = 4,
466 MSF_WriteLocked = 8,
467 MSF_ReadLocked = 16,
468 MSF_WriteLocksPending = 32,
469 MSF_GuardedLocked = 64,
470 };
471
472 /*! \class MutexReadWriteSuspendable
473 \brief A readers-writer mutex class that is able to be suspended
474 */
475 class MutexReadWriteSuspendable
476 {
477 private:
478 Mutex m_access;
479 volatile std::atomic_int m_writeRef;
480 volatile std::atomic<XsThreadId> m_writeLocked;
481 volatile std::atomic_int m_writeLocksPending;
482 volatile std::atomic_int m_writeLockSuspendCount;
483 XsThreadId* m_readLocked;
484
485 int m_readLockMax;
486 int m_readLockCount;
487 friend class LockSuspendable;
488 MutexReadWriteSuspendable(MutexReadWriteSuspendable const&) = delete;
489 MutexReadWriteSuspendable& operator=(MutexReadWriteSuspendable const&) = delete;
490 MutexReadWriteSuspendable(MutexReadWriteSuspendable &&) = delete;
491 MutexReadWriteSuspendable& operator=(MutexReadWriteSuspendable &&) = delete;
492 public:
493
494 /*! \brief An enum class that holds a three different modes of a suspendable mutex
495 */
496 enum class Mode
497 {
498 Read,
499 Write,
500 SuspendedWrite
501 };
502
503 inline MutexReadWriteSuspendable()
504 : m_writeRef(0)
505 , m_writeLocked(0)
506 , m_writeLocksPending(0)
507 , m_writeLockSuspendCount(0)
508 , m_readLockMax(32)
509 , m_readLockCount(0)
510 {
511 m_readLocked = new XsThreadId[m_readLockMax];
512 }
513
514 inline ~MutexReadWriteSuspendable()
515 {
516 delete[] m_readLocked;
517 }
518 private:
519 inline void addReadLock(XsThreadId cid)
520 {
521 if (m_readLockCount == m_readLockMax)
522 {
523 m_readLockMax = m_readLockMax*2;
524 XsThreadId* tmp = new XsThreadId[m_readLockMax];
525 memcpy(tmp, m_readLocked, ((unsigned int)m_readLockCount)*sizeof(XsThreadId));
526 delete[] m_readLocked;
527 m_readLocked = tmp;
528 }
529 m_readLocked[m_readLockCount++] = cid;
530 }
531
532 inline void enterAtomic()
533 {
534 m_access.claimMutex();
535 }
536
537 inline void leaveAtomic()
538 {
539 m_access.releaseMutex();
540 }
541
542 protected:
543
544 /*! \brief Claims (locks) a mutex using a given mode
545 \param mode The mode to use
546 \returns True if successful
547 */
548 inline bool claimMutex(Mode mode)
549 {
550 XsThreadId cid = xsGetCurrentThreadId();
551 // write lock
552 switch (mode)
553 {
554 case Mode::Write:
555 enterAtomic();
556 ++m_writeLocksPending;
557 while(1)
558 {
559 bool readFail = false;
560 if (m_writeLocked == 0 || (m_writeLockSuspendCount && m_writeLockSuspendCount == m_writeRef))
561 {
562 for (int i = 0; i < m_readLockCount; ++i)
563 {
564 if (m_readLocked[i] != cid)
565 {
566 readFail = true;
567 break;
568 }
569 }
570 }
571
572 if ((m_writeLocked != cid && (m_writeLocked != 0 || readFail))
573 || (readFail && m_writeLockSuspendCount && m_writeLockSuspendCount == m_writeRef))
574 {
575 leaveAtomic();
576 xsYield(); // wait for other locks to end
577 enterAtomic();
578 }
579 else
580 {
581 ++m_writeRef;
582 --m_writeLocksPending;
583 m_writeLocked = cid;
584 leaveAtomic();
585 return true;
586 }
587 }
588 break;
589
590 case Mode::Read:
591 while (1)
592 {
593 enterAtomic();
594 bool readGot = false;
595 if ((m_writeLocked == 0 && m_writeLocksPending == 0)
596 || m_writeLocked == cid
597 || (m_writeLockSuspendCount && m_writeLockSuspendCount == m_writeRef))
598 {
599 readGot = true;
600 }
601 else
602 {
603 for (int i = 0; i < m_readLockCount; ++i)
604 {
605 if (m_readLocked[i] == cid)
606 {
607 readGot = true;
608 break;
609 }
610 }
611 }
612
613 if (readGot)
614 {
615 addReadLock(cid);
616 leaveAtomic();
617 return true;
618 }
619 leaveAtomic();
620 // wait for write lock to end
621 xsYield();
622 }
623 break;
624
625 case Mode::SuspendedWrite:
626 enterAtomic();
627 ++m_writeLocksPending;
628 while(1)
629 {
630 if (m_writeLocked != cid && m_writeLocked != 0)
631 {
632 leaveAtomic();
633 xsYield(); // wait for other write locks to end
634 enterAtomic();
635 }
636 else
637 {
638 ++m_writeRef;
639 --m_writeLocksPending;
640 m_writeLocked = cid;
641 ++m_writeLockSuspendCount;
642 leaveAtomic();
643 return true;
644 }
645 }
646 break;
647
648 default:
649 break;
650 }
651
652 assert(0);
653 return false;
654 }
655
656 /*! \brief Claims (locks) a mutex for read or write modes
657 \param write If set to true write mode is used, otherwise read mode
658 \returns True if successful
659 \note Made for backwards compatibility
660 */
661 inline bool claimMutex(bool write)
662 {
663 return claimMutex(write ? Mode::Write : Mode::Read);
664 }
665
666 /*! \brief Downgrade an existing write lock to a read lock
667 */
668 inline bool downgradeToRead(bool decreaseSuspend)
669 {
670 XsThreadId cid = xsGetCurrentThreadId();
671 enterAtomic();
672 if (m_writeLocked == cid)
673 {
674 if (decreaseSuspend)
675 --m_writeLockSuspendCount;
676 if (--m_writeRef == 0)
677 {
678 m_writeLocked = 0;
679 m_writeLockSuspendCount = 0;
680 }
681 addReadLock(cid);
682 leaveAtomic();
683 return true;
684 }
685 leaveAtomic();
686 return false;
687 }
688
689 /*! \brief Suspend an existing write lock so read locks are allowed, but do not allow other write locks
690 */
691 inline bool suspendWriteLock()
692 {
693 XsThreadId cid = xsGetCurrentThreadId();
694 enterAtomic();
695 if (m_writeLocked == cid)
696 {
697 ++m_writeLockSuspendCount;
698 leaveAtomic();
699 return true;
700 }
701 leaveAtomic();
702 return false;
703 }
704
705 /*! \brief Resumes an existing write lock so read locks are no longer allowed
706 */
707 inline bool resumeWriteLock()
708 {
709 XsThreadId cid = xsGetCurrentThreadId();
710 enterAtomic();
711 if (m_writeLocked == cid)
712 {
713 if (m_writeLockSuspendCount-- == m_writeRef)
714 {
715 // wait for all read locks to end
716 while(1)
717 {
718 bool stillReading = false;
719 for (int i = 0; i < m_readLockCount; ++i)
720 {
721 if (m_readLocked[i] != cid)
722 {
723 stillReading = true;
724 break;
725 }
726 }
727
728 if (!stillReading)
729 {
730 leaveAtomic();
731 return true;
732 }
733 leaveAtomic();
734 xsYield();
735 enterAtomic();
736 }
737 }
738 leaveAtomic();
739 return true;
740 }
741 leaveAtomic();
742 return false;
743 }
744
745 /*! \brief Releases (unlocks) a mutex for read or write modes
746 \param write If set to true, write mode is used, otherwise read mode
747 \param decreaseSuspendCount If set to true, it will decrease a suspend count
748 \returns True if successful
749 */
750 inline bool releaseMutex(bool write, bool decreaseSuspendCount)
751 {
752 XsThreadId cid = xsGetCurrentThreadId();
753 enterAtomic();
754 if (write)
755 {
756 if (m_writeLocked == cid)
757 {
758 if (decreaseSuspendCount)
759 --m_writeLockSuspendCount;
760
761 if (--m_writeRef == 0)
762 {
763 m_writeLockSuspendCount = 0;
764 m_writeLocked = 0;
765 }
766 }
767 else
768 {
769 leaveAtomic();
770 return false;
771 }
772 }
773 else
774 {
775 if (m_readLockCount == 0)
776 {
777 leaveAtomic();
778 return false;
779 }
780 for (int i = m_readLockCount-1; i >= 0; --i)
781 if (m_readLocked[i] == cid)
782 {
783 for (int j = i+1; j < m_readLockCount; ++j)
784 m_readLocked[j-1] = m_readLocked[j];
785 --m_readLockCount;
786 break;
787 }
788 }
789 leaveAtomic();
790 return true;
791 }
792
793 /*! \brief Releases (unlocks) a mutex using a given mode
794 \param mode The mode to use
795 \param decreaseSuspendCount If set to true, it will decrease a suspend count
796 \returns True if successful
797 */
798 inline bool releaseMutex(Mode mode, bool decreaseSuspendCount)
799 {
800 return releaseMutex(mode != Mode::Read, decreaseSuspendCount);
801 }
802 public:
803
804 /*! \returns The status of the current thread
805 \sa MutexStatusFlags
806 */
807 int status() const volatile
808 {
809 int rv = 0;
810 XsThreadId cid = xsGetCurrentThreadId();
811 const_cast<MutexReadWriteSuspendable*>(this)->enterAtomic();
812 if (m_writeRef)
813 {
814 rv |= MSF_WriteLocked;
815 if (m_writeLocked == cid)
816 rv |= MSF_HaveWriteLock;
817 if (m_writeLockSuspendCount == m_writeRef)
818 rv |= MSF_WriteLockSuspended;
819 }
820 if (m_writeLocksPending)
821 rv |= MSF_WriteLocksPending;
822 if (m_readLockCount)
823 rv |= MSF_ReadLocked;
824 for (int i = 0; i < m_readLockCount; ++i)
825 {
826 if (m_readLocked[i] == cid)
827 {
828 rv |= MSF_HaveReadLock;
829 break;
830 }
831 }
832 const_cast<MutexReadWriteSuspendable*>(this)->leaveAtomic();
833 return rv;
834 }
835
836 #ifndef XSENS_DEBUG
837 protected:
838 // these functions should only be used internally and in assert statements
839 #endif
840 /*! \returns True if is has an write lock
841 */
842 inline bool haveWriteClaim() const volatile
843 {
844 return (status() & MSF_HaveWriteLock) != 0;
845 }
846
847 /*! \returns True if is has a read lock
848 */
849 inline bool haveReadClaim() const volatile
850 {
851 return (status() & (MSF_HaveWriteLock | MSF_HaveReadLock)) != 0;
852 }
853 };
854
855 /*! \class Lock
856 \brief A base class for a ock
857 */
858 class Lock {
859 private:
860 Mutex* m_mutex;
861 bool m_locked;
862
863 Lock(Lock const&) = delete;
864 Lock& operator=(Lock const&) = delete;
865 Lock(Lock &&) = delete;
866 Lock& operator=(Lock &&) = delete;
867
868 public:
869
870 /*! \brief Constructs a lock a given mutex
871 \param mutex The pointer to a mutex to lock
872 */
873 inline Lock(Mutex* mutex) : m_mutex(mutex), m_locked(false)
874 {
875 m_locked = m_mutex->claimMutex();
876 }
877
878 /*! \brief Constructs a lock a given mutex
879 \param mutex The pointer to a mutex to lock
880 \param lockit If set to true then it will lock a mutex
881 */
882 inline Lock(Mutex* mutex, bool lockit) : m_mutex(mutex), m_locked(false)
883 {
884 if (lockit)
885 m_locked = m_mutex->claimMutex();
886 }
887
888 /*! \brief Constructs a lock a given mutex
889 \param mutex The pointer to a mutex to lock
890 \param lockit If is not set to an unlocked state then it will lock it
891 */
892 inline Lock(Mutex* mutex, LockState lockit) : m_mutex(mutex), m_locked(false)
893 {
894 if (lockit != LS_Unlocked)
895 m_locked = m_mutex->claimMutex();
896 }
897 inline ~Lock()
898 {
899 unlock();
900 }
901
902 /*! \brief Locks the unlocked mutex
903 \returns True if the mutex is successfully locked
904 */
905 inline bool lock()
906 {
907 if (!m_locked)
908 return (m_locked = m_mutex->claimMutex()) != 0;
909 return true;
910 }
911
912 /*! \brief Unlocks the locked mutex
913 \returns True if the mutex is successfully unlocked
914 */
915 inline bool unlock() noexcept
916 {
917 if (m_locked)
918 {
919 #ifndef __GNUC__
920 #pragma warning(suppress: 4706)
921 #endif
922 return !(m_locked = !m_mutex->releaseMutex());
923 }
924 return true;
925 }
926
927 /*! \brief Tries to lock the unlocked mutex
928 \returns True if the mutex is successfully locked
929 */
930 inline bool tryLock()
931 {
932 if (!m_locked)
933 return (m_locked = m_mutex->tryClaimMutex());
934 return true;
935 }
936
937 /*! \returns True if the mutex is locked*/
938 inline bool isLocked() const
939 {
940 return m_locked;
941 }
942 };
943
944 /*! \class LockReadWrite
945 \brief A readers-writer lock class
946 */
947 class LockReadWrite {
948 private:
949 MutexReadWrite* m_mutex;
950 bool m_lockedR;
951 bool m_lockedW;
952
953 LockReadWrite(LockReadWrite const&) = delete;
954 LockReadWrite& operator=(LockReadWrite const&) = delete;
955 LockReadWrite(LockReadWrite &&) = delete;
956 LockReadWrite& operator=(LockReadWrite &&) = delete;
957 public:
958
959 /*! \brief Consturctor
960 */
961 inline LockReadWrite(MutexReadWrite* mutex, LockState lockState = LS_Unlocked) : m_mutex(mutex), m_lockedR(false), m_lockedW(false)
962 {
963 #if defined(XSENS_DEBUG)
964 assert(m_mutex != NULL);
965 #endif
966
967 if (lockState == LS_Read)
968 lock(false);
969 else if (lockState == LS_Write)
970 lock(true);
971 else
972 assert(lockState != LS_SuspendedWrite);
973 }
974 inline ~LockReadWrite()
975 {
976 unlock();
977 }
978
979 /*! \brief Make sure that the lock has exactly the given lock state
980 \details The lock will be upgraded/downgraded as required, possibly unlocking in between
981 \param write If set to true, write mode is used, otherwise read mode
982 \returns True if successfully locked
983 */
984 inline bool lock(bool write)
985 {
986 if (write)
987 {
988 if (m_lockedW)
989 return true;
990 if (m_lockedR)
991 unlock();
992 m_lockedW = m_mutex->claimMutex(true);
993 assert(m_lockedW);
994 return m_lockedW;
995 }
996 else
997 {
998 if (m_lockedW)
999 {
1000 m_lockedR = m_mutex->downgradeToRead();
1001 m_lockedW = false;
1002 assert(m_lockedR);
1003 }
1004 if (!m_lockedR)
1005 m_lockedR = m_mutex->claimMutex(false);
1006 assert(m_lockedR);
1007 return m_lockedR;
1008 }
1009 }
1010
1011 /*! \brief Convenience function that accepts the generic LockState, forwards to lock(bool)
1012 \param ls If set not to read lock state then it will lock the mutex
1013 \returns True if successfully locked
1014 */
1015 inline bool lock(LockState ls)
1016 {
1017 assert(ls == LS_Read || ls == LS_Write);
1018 return lock(ls != LS_Read);
1019 }
1020 /*! \brief Convenience function for lock(false);
1021 \return True if successful
1022 */
1023 inline bool lockRead() { return lock(false); }
1024
1025 /*! \brief Convenience function for lock(true);
1026 \return True if successful
1027 */
1028 inline bool lockWrite() { return lock(true); }
1029
1030 /*! \brief Unlocks the write or read locked mutex
1031 \returns True if the mutex is successfully unlocked. False if it was not locked.
1032 */
1033 inline bool unlock() noexcept
1034 {
1035 if (m_lockedW)
1036 {
1037 assert(!m_lockedR);
1038 m_lockedW = false;
1039 return m_mutex->releaseMutex(true);
1040 }
1041 if (m_lockedR)
1042 {
1043 m_lockedR = false;
1044 return m_mutex->releaseMutex(false);
1045 }
1046 return false;
1047 }
1048
1049 /*! \brief Tries to lock the write/read unlocked mutex before a given time runs out
1050 \param write If set to true, write mode is used, otherwise read mode
1051 \param timeout The timeout value in ms
1052 \returns True if the mutex is successfully locked
1053 */
1054 inline bool tryLock(bool write, uint32_t timeout)
1055 {
1056 if (write)
1057 {
1058 if (m_lockedW)
1059 return true;
1060 if (m_lockedR)
1061 unlock();
1062 m_lockedW = m_mutex->tryClaimMutex(true, timeout);
1063 assert(m_lockedW);
1064 return m_lockedW;
1065 }
1066 else
1067 {
1068 if (m_lockedW)
1069 {
1070 m_lockedR = m_mutex->downgradeToRead();
1071 m_lockedW = false;
1072 assert(m_lockedR);
1073 }
1074 if (!m_lockedR)
1075 m_lockedR = m_mutex->tryClaimMutex(false, timeout);
1076 assert(m_lockedR);
1077 return m_lockedR;
1078 }
1079 }
1080
1081 /*! \returns true if the lock has at least the given state
1082 \param write If set to true, write mode is used, otherwise read mode
1083 */
1084 inline bool isLocked(bool write) const volatile
1085 {
1086 return (!write && m_lockedR) || m_lockedW;
1087 }
1088
1089 /*! \returns True if the mutex has a write lock
1090 \note Do not use this function internally! The mutex may have a write claim, while the lock does not, but this function will return true.
1091 */
1092 inline bool haveWriteClaim() const volatile
1093 {
1094 return m_mutex->haveWriteClaim();
1095 }
1096 };
1097
1098 /*! \brief A two-layer mutex, typically used for status+data protection
1099 \details The class provides a main suspendable mutex, which can be used for all kinds of status updates and a
1100 deeper guarded mutex, which will enforce the main mux to be locked before allowing itself to be locked.
1101
1102 \note The main purpose of this is for multi-threaded data handling in which the mian mux guards the state of the device,
1103 and the guarded mux guards data access.
1104 */
1105 class GuardedMutex : private MutexReadWriteSuspendable
1106 {
1107 private:
1108 Mutex m_guarded;
1109 friend class LockGuarded;
1110 friend class LockSuspendable;
1111
1112 GuardedMutex(GuardedMutex const&) = delete;
1113 GuardedMutex& operator=(GuardedMutex const&) = delete;
1114 GuardedMutex(GuardedMutex &&) = delete;
1115 GuardedMutex& operator=(GuardedMutex &&) = delete;
1116
1117 public:
1118
1119 /*! \brief Constructor
1120 */
1121 inline GuardedMutex()
1122 {
1123 }
1124
1125 /*! \brief Destructor
1126 */
1127 inline ~GuardedMutex()
1128 {
1129 }
1130
1131 /*! \returns true if the mutex is claimed successfully
1132 */
1133 inline bool claimMutex()
1134 {
1135 MutexReadWriteSuspendable::claimMutex(Mode::Read);
1136 return m_guarded.claimMutex();
1137 }
1138
1139 /*! \returns true if the mutex is released successfully
1140 */
1141 inline bool releaseMutex()
1142 {
1143 m_guarded.releaseMutex();
1144 MutexReadWriteSuspendable::releaseMutex(false, false);
1145 return true;
1146 }
1147
1148 /*! \returns The reference to this mutex
1149 \note Give access to the base class for directly checking the state of the mux
1150 */
1151 MutexReadWriteSuspendable& suspendable() { return *this; }
1152
1153 /*! \brief Check if the guarded mutex is equal to the supplied mutex
1154 \param mutex The supplied mutex
1155 \returns True if it is equal
1156 */
1157 inline bool isUsing(Mutex const* mutex) const
1158 {
1159 return &m_guarded == mutex;
1160 }
1161
1162 /*! \returns The status of this mutex*/
1163 int status() const volatile
1164 {
1165 return MutexReadWriteSuspendable::status() | (m_guarded.isLocked() ? MSF_GuardedLocked : 0);
1166 }
1167
1168 #ifdef XSENS_DEBUG
1169 // this function is only intended as a debug function for use in assert statements
1170 inline bool haveGuardedLock() const
1171 {
1172 return m_guarded.haveLock();
1173 }
1174 #endif
1175
1176 #ifndef XSENS_DEBUG
1177 protected:
1178 // these functions should only be used internally and in assert statements
1179 #endif
1180 using MutexReadWriteSuspendable::haveWriteClaim;
1181 using MutexReadWriteSuspendable::haveReadClaim;
1182 };
1183
1184 /*! \class LockSuspendable
1185 \brief A readers-writer lock class that is able to be suspended
1186 */
1187 class LockSuspendable {
1188 private:
1189 MutexReadWriteSuspendable* m_mutex;
1190 bool m_lockedR;
1191 bool m_lockedW;
1192 bool m_iSuspended; // Read: I suspended the write lock, this does not mean that it actually IS suspended
1193
1194 LockSuspendable(LockSuspendable const&) = delete;
1195 LockSuspendable& operator=(LockSuspendable const&) = delete;
1196 LockSuspendable(LockSuspendable &&) = delete;
1197 LockSuspendable& operator=(LockSuspendable &&) = delete;
1198
1199 public:
1200
1201 /*! \brief Constructs a lock using a suspendable readers-writer mutex
1202 */
1203 inline LockSuspendable(MutexReadWriteSuspendable* mutex, LockState lockState) : m_mutex(mutex), m_lockedR(false), m_lockedW(false), m_iSuspended(false)
1204 {
1205 #if defined(XSENS_DEBUG)
1206 assert(m_mutex != NULL);
1207 #endif
1208
1209 if (lockState != LS_Unlocked)
1210 lock(lockState);
1211 }
1212
1213 /*! \brief Constructs a lock using a guarded mutex
1214 */
1215 inline LockSuspendable(GuardedMutex* mutex, LockState lockState) : m_mutex(mutex), m_lockedR(false), m_lockedW(false), m_iSuspended(false)
1216 {
1217 #if defined(XSENS_DEBUG)
1218 assert(m_mutex != NULL);
1219 #endif
1220
1221 if (lockState != LS_Unlocked)
1222 lock(lockState);
1223 }
1224
1225 inline ~LockSuspendable()
1226 {
1227 unlock();
1228 }
1229
1230 /*! \brief Make sure that the lock has exactly the given lock state
1231 \details The lock will be upgraded/downgraded as required, possibly unlocking in between
1232 \param desiredLockState If set not to read lock state then it will lock the mutex
1233 \returns True if successfully locked
1234 */
1235 inline bool lock(LockState desiredLockState)
1236 {
1237 switch (desiredLockState)
1238 {
1239 case LS_Write:
1240 if (m_lockedW)
1241 return resume();
1242 if (m_lockedR)
1243 unlock();
1244 m_lockedW = m_mutex->claimMutex(MutexReadWriteSuspendable::Mode::Write);
1245 assert(m_lockedW);
1246 return m_lockedW;
1247
1248 case LS_SuspendedWrite:
1249 if (m_lockedW)
1250 return suspend();
1251 if (m_lockedR)
1252 unlock();
1253 m_lockedW = m_mutex->claimMutex(MutexReadWriteSuspendable::Mode::SuspendedWrite);
1254 m_iSuspended = m_lockedW;
1255 assert(m_lockedW);
1256 return m_lockedW;
1257
1258 case LS_Read:
1259 if (m_lockedW)
1260 {
1261 m_lockedR = m_mutex->downgradeToRead(m_iSuspended);
1262 m_iSuspended = false;
1263 m_lockedW = false;
1264 assert(m_lockedR);
1265 }
1266 if (!m_lockedR)
1267 m_lockedR = m_mutex->claimMutex(MutexReadWriteSuspendable::Mode::Read);
1268 assert(m_lockedR);
1269 return m_lockedR;
1270
1271 case LS_Unlocked:
1272 return unlock();
1273
1274 default:
1275 assert(0);
1276 return false;
1277 }
1278 }
1279
1280 /*! \brief Convenience function that accepts the boolean write value, forwards to lock(LockState)
1281 \param write If set to true, write mode is used, otherwise read mode
1282 \returns True if successfully locked
1283 */
1284 inline bool lock(bool write)
1285 {
1286 return lock(write ? LS_Write : LS_Read);
1287 }
1288
1289 /*! \brief Convenience function for lock(LS_Read);
1290 \return True if successful
1291 */
1292 inline bool lockRead() { return lock(LS_Read); }
1293
1294 /*! \brief Convenience function for lock(LS_Write);
1295 \return True if successful
1296 */
1297 inline bool lockWrite() { return lock(LS_Write); }
1298
1299 /*! \brief Convenience function for lock(LS_SuspendedWrite);
1300 \return True if successful
1301 */
1302 inline bool lockSuspendedWrite() { return lock(LS_SuspendedWrite); }
1303
1304 /*! \brief Suspend a write lock, allowing readers access, but preventing others from getting a write lock
1305 \returns True if successful or if already suspended
1306 */
1307 inline bool suspend()
1308 {
1309 assert(m_lockedW);
1310 if (m_iSuspended)
1311 return true;
1312 m_iSuspended = true;
1313 return m_mutex->suspendWriteLock();
1314 }
1315
1316 /*! \brief Resume a write lock
1317 \return True if successful or if already resuming
1318 */
1319 inline bool resume()
1320 {
1321 assert(m_lockedW);
1322 if (!m_iSuspended)
1323 return true;
1324 m_iSuspended = false;
1325 return m_mutex->resumeWriteLock();
1326 }
1327
1328 /*! \returns True if mutex is suspended
1329 */
1330 inline bool isSuspended() const
1331 {
1332 return m_iSuspended;
1333 }
1334
1335 /*! \returns True if mutex is suspended
1336 \note This function check the current status of the mutex to tell whether it is actually suspended
1337 */
1338 inline bool mutexIsSuspended() const volatile
1339 {
1340 return (m_mutex->status() & (MSF_WriteLockSuspended | MSF_WriteLocked)) == (MSF_WriteLockSuspended | MSF_WriteLocked);
1341 }
1342
1343 /*! \brief Unlocks the write or read locked mutex
1344 \returns True if the mutex is successfully unlocked. False if it was not locked.
1345 */
1346 inline bool unlock() noexcept
1347 {
1348 if (m_lockedW)
1349 {
1350 assert(!m_lockedR);
1351 m_lockedW = false;
1352 bool s = m_iSuspended;
1353 m_iSuspended = false;
1354 return m_mutex->releaseMutex(true, s);
1355 }
1356 if (m_lockedR)
1357 {
1358 m_lockedR = false;
1359 return m_mutex->releaseMutex(false, false);
1360 }
1361 return false;
1362 }
1363
1364 /*! \returns True if the lock has at least the given state. A suspended write lock is treated as a read lock.
1365 \param minimumState The minimum lock state to check with
1366 */
1367 inline bool isLocked(LockState minimumState) const
1368 {
1369 bool sus = isSuspended();
1370 if (minimumState == LS_Write)
1371 return m_lockedW && !sus;
1372 if (minimumState == LS_SuspendedWrite)
1373 return m_lockedW && sus;
1374 if (minimumState == LS_Read)
1375 return m_lockedW || m_lockedR;
1376 assert(minimumState == LS_Unlocked);
1377 return true;
1378 }
1379
1380 /*! \brief Check if the lock is using the supplied mutex
1381 \param mutex The supplied suspendable readers-writer mutex
1382 \returns True if it is equal
1383 */
1384 bool isUsing(MutexReadWriteSuspendable const* mutex) const
1385 {
1386 return m_mutex == mutex;
1387 }
1388
1389 /*! \brief Check if the lock is using the supplied mutex
1390 \param mutex The supplied guarded mutex
1391 \returns True if it is equal
1392 */
1393 bool isUsing(GuardedMutex const* mutex) const
1394 {
1395 return m_mutex == mutex;
1396 }
1397 };
1398
1399 /*! \class LockGuarded
1400 \brief A guarded lock class
1401 */
1402 class LockGuarded {
1403 private:
1404 GuardedMutex* m_mutex;
1405 bool m_locked;
1406
1407 LockGuarded(LockGuarded const&) = delete;
1408 LockGuarded& operator=(LockGuarded const&) = delete;
1409 LockGuarded(LockGuarded &&) = delete;
1410 LockGuarded& operator=(LockGuarded &&) = delete;
1411
1412 public:
1413
1414 /*! \brief Constructs a guarded lock using a guarded mutex
1415 */
1416 inline LockGuarded(GuardedMutex* mutex, bool lockit = true) : m_mutex(mutex), m_locked(false)
1417 {
1418 if (lockit)
1419 m_locked = m_mutex->claimMutex();
1420 }
1421
1422 /*! \brief Constructs a guarded lock using a guarded mutex and a lock state
1423 */
1424 inline LockGuarded(GuardedMutex* mutex, LockState lockit) : m_mutex(mutex), m_locked(false)
1425 {
1426 if (lockit != LS_Unlocked)
1427 m_locked = m_mutex->claimMutex();
1428 }
1429
1430 /*! \brief Destructor
1431 */
1432 inline ~LockGuarded()
1433 {
1434 unlock();
1435 }
1436
1437 /*! \brief Locks the unlocked mutex
1438 \returns True if the mutex is successfully locked
1439 */
1440 inline bool lock()
1441 {
1442 if (!m_locked)
1443 return (m_locked = m_mutex->claimMutex()) != 0;
1444 return true;
1445 }
1446
1447 /*! \brief Unlocks the locked mutex
1448 \returns True if the mutex is successfully unlocked
1449 */
1450 inline bool unlock() noexcept
1451 {
1452 if (m_locked)
1453 {
1454 #ifndef __GNUC__
1455 #pragma warning(suppress: 4706)
1456 #endif
1457 return !(m_locked = !m_mutex->releaseMutex());
1458 }
1459 return true;
1460 }
1461
1462 /*! \returns True if the mutex is locked by this lock
1463 */
1464 inline bool isLocked() const
1465 {
1466 return m_locked;
1467 }
1468
1469 /*! \brief Check if the lock is using the supplied mutex
1470 \param mutex The supplied guarded mutex
1471 \returns True if it is equal
1472 */
1473 bool isUsing(GuardedMutex const* mutex) const
1474 {
1475 return m_mutex == mutex;
1476 }
1477
1478 /*! \brief Check if the lock is using the supplied mutex
1479 \param mutex The supplied suspendable readers-writer mutex
1480 \returns True if it is equal
1481 */
1482 bool isUsing(MutexReadWriteSuspendable const* mutex) const
1483 {
1484 return m_mutex == mutex;
1485 }
1486
1487 /*! \brief Check if the lock is using the supplied mutex
1488 \param mutex The supplied generic mutex
1489 \returns True if it is equal
1490 */
1491 bool isUsing(Mutex const* mutex) const
1492 {
1493 return m_mutex->isUsing(mutex);
1494 }
1495 };
1496
1497 /*! \class ProtectedValue
1498 \brief A protected value class
1499 */
1500 template <typename K>
1501 class ProtectedValue {
1502 private:
1503 mutable LockReadWrite* m_lock;
1504 public:
1505
1506 /*! \brief Constructs a protected value using a readers-writer mutex
1507 */
1508 ProtectedValue(MutexReadWrite* mutex, bool writeLock = false)
1509 {
1510 m_lock = new LockReadWrite(mutex);
1511 m_lock->lock(writeLock);
1512 }
1513
1514 /*! \brief Constructs a protected value using a reference of another protected value
1515 */
1516 ProtectedValue(const ProtectedValue &pv)
1517 {
1518 m_lock = pv.m_lock;
1519 m_value = pv.m_value;
1520 pv.m_lock = NULL;
1521 }
1522
1523 /*! \brief Destructor
1524 */
1525 ~ProtectedValue()
1526 {
1527 if (m_lock)
1528 delete m_lock;
1529 }
1530
1531 /*! \brief Assignment operator, copies contents from the \a pv protected value
1532 \param pv : The protected value to copy from
1533 */
1534 void operator = (const ProtectedValue& pv)
1535 {
1536 if (&pv == this)
1537 return;
1538
1539 assert(pv.m_lock);
1540 m_lock = pv.m_lock;
1541 m_value = pv.m_value;
1542 pv.m_lock = NULL;
1543 }
1544
1545 K m_value; //!< A type name of this class
1546 };
1547
1548 /*! \class Semaphore
1549 \brief A semaphore class
1550 */
1551 class Semaphore {
1552 protected:
1553 #ifdef _WIN32
1554 HANDLE *m_handleList; //!< The list of handles on the Semaphore
1555 #else
1556 char *m_semname; //!< A name of the semaphore
1557 sem_t *m_handle; //!< A semaphore's handle
1558 #endif
1559 uint32_t m_nofHandles; //!< A number of the semaphore's handles
1560
1561 Semaphore(Semaphore const&) = delete;
1562 Semaphore& operator=(Semaphore const&) = delete;
1563 Semaphore(Semaphore &&) = delete;
1564 Semaphore& operator=(Semaphore &&) = delete;
1565
1566 public:
1567
1568 /*! \brief Waits for an infinite time or until the semaphore is released
1569 \returns True if the semaphore is released
1570 */
1571 bool wait1();
1572
1573 /*! \brief Waits until time-out interval elapses or until the semaphore is released
1574 \param timeout The timeout value to use
1575 \returns True if the semaphore is released
1576 */
1577 bool wait1(uint32_t timeout);
1578
1579 /*! \brief Increases the count of the specified semaphore object by a specified amount
1580 \param increment The amount by which the semaphore object's current count is to be increased
1581 \returns The amount of the semaphore object's previous count
1582 */
1583 int32_t post(int32_t increment = 1) noexcept;
1584 #ifdef _WIN32
1585 /*! \brief Constructor
1586 */
1587 Semaphore(int32_t initVal = 0, uint32_t nofOtherHandles = 0, HANDLE *otherHandles = NULL);
1588 #else
1589 /*! \brief Constructor
1590 */
1591 Semaphore(int32_t initVal = 0, uint32_t nofOtherHandles = 0, sem_t *otherHandles = NULL);
1592 #endif
1593 /*! \brief Destructor
1594 */
1595 ~Semaphore();
1596 };
1597
1598 /*! \class WaitCondition
1599 * \brief A platform independent wait condition implementation
1600 *
1601 * Wait conditions are used to halt consumer threads until changes are made to data they operate on.
1602 *
1603 * Creating the wait condition:
1604 * \code
1605 * Mutex mut;
1606 * WaitCondition wc(&mut);
1607 * \endcode
1608 *
1609 * Consumer thread:
1610 * \code
1611 * void func()
1612 * {
1613 * Lock locker(&mut);
1614 *
1615 * if (!wc.wait()) // unlocks the mutex and waits for a signal
1616 * // the mutex is claimed
1617 * return;
1618 *
1619 * // mutex is claimed
1620 * // copy data
1621 * lock.unlock();
1622 * // work with data
1623 * }
1624 * \endcode
1625 *
1626 * Feeder thread:
1627 * \code
1628 * void func()
1629 * {
1630 * Lock locker(&mut);
1631 *
1632 * // update data
1633 * wc.signal(); // signal that changes have been made
1634 * // alternatively, use wc.broadcast() to allow multiple consumers to handle the data
1635 * }
1636 * \endcode
1637 */
1638 class WaitCondition
1639 {
1640 WaitCondition(WaitCondition const&) = delete;
1641 WaitCondition& operator=(WaitCondition const&) = delete;
1642 WaitCondition(WaitCondition &&) = delete;
1643 WaitCondition& operator=(WaitCondition &&) = delete;
1644
1645 public:
1646 explicit WaitCondition(Mutex &m);
1647 ~WaitCondition();
1648
1649 void signal();
1650 void broadcast();
1651 bool wait();
1652 bool wait(uint32_t timeout);
1653 private:
1654 #ifdef _WIN32
1655 CONDITION_VARIABLE m_cond;
1656 #else
1657 pthread_cond_t m_cond;
1658 pthread_condattr_t m_condattr;
1659 #ifdef __APPLE__
1660 int m_clockId;
1661 #else
1662 clockid_t m_clockId;
1663 #endif
1664 #endif
1665 Mutex &m_mutex;
1666 };
1667
1668 /*! \brief An event that can be set/reset and that can be waited for
1669 \details The WaitEvent is intended for 1-1 thread synchronization, not 1-N thread synchronization
1670 */
1671 class WaitEvent
1672 {
1673 WaitEvent(WaitEvent const&) = delete;
1674 WaitEvent& operator=(WaitEvent const&) = delete;
1675 WaitEvent(WaitEvent &&) = delete;
1676 WaitEvent& operator=(WaitEvent &&) = delete;
1677
1678 public:
1679 WaitEvent();
1680 ~WaitEvent();
1681
1682 void terminate();
1683 bool wait();
1684 void set();
1685 void reset();
1686
1687 private:
1688 #if defined(_WIN32)
1689 HANDLE m_event;
1690 #else
1691 pthread_mutex_t m_mutex;
1692 pthread_cond_t m_cond;
1693 bool m_triggered;
1694 #endif
1695 volatile std::atomic_int m_waiterCount;
1696 bool m_terminating;
1697 };
1698 } // namespace xsens
1699
1700 #ifndef __GNUC__
1701 #pragma warning(default: 4127)
1702 #endif
1703
1704 #endif