StateOS
Loading...
Searching...
No Matches
osmutex.h
1/******************************************************************************
2
3 @file StateOS: osmutex.h
4 @author Rajmund Szymanski
5 @date 17.11.2025
6 @brief This file contains definitions for StateOS.
7
8 ******************************************************************************
9
10 Copyright (c) 2018-2022 Rajmund Szymanski. All rights reserved.
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to
14 deal in the Software without restriction, including without limitation the
15 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
16 sell copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included
20 in all copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
23 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28 IN THE SOFTWARE.
29
30 ******************************************************************************/
31
32#ifndef __STATEOS_MTX_H
33#define __STATEOS_MTX_H
34
35#include "oskernel.h"
36#include "osclock.h"
37
43
44/* -------------------------------------------------------------------------- */
45
47#define mtxNormal 0U
48#define mtxErrorCheck 1U
49#define mtxRecursive 2U
50#define mtxDefault mtxNormal
51#define mtxTypeMASK ( mtxNormal | mtxErrorCheck | mtxRecursive )
52
54#define mtxPrioNone 0U
55#define mtxPrioInherit 4U
56#define mtxPrioProtect 8U
57 // at the mutex priority (ceiling), a task with a higher priority cannot lock it
58#define mtxPrioMASK ( mtxPrioNone | mtxPrioInherit | mtxPrioProtect )
59
61#define mtxStalled 0U
62#define mtxRobust 16U
63
65#define mtxInconsistent 32U
66
67#define mtxMASK ( mtxTypeMASK | mtxPrioMASK | mtxRobust | mtxInconsistent )
68
69/* -------------------------------------------------------------------------- */
70
71#define MTX_LIMIT ( 0U-1 )
72
76
77struct __mtx
78{
79 obj_t obj;
80
81 tsk_t * owner;
82 unsigned mode;
83 unsigned count;
84 unsigned prio;
85 mtx_t * list;
86};
87
88typedef struct __mtx mtx_id [];
89
90/******************************************************************************
91 *
92 * Name : _MTX_INIT
93 *
94 * Description : create and initialize a mutex object
95 *
96 * Parameters
97 * mode : mutex mode (mutex type + mutex protocol + mutex robustness)
98 * type: mtxNormal or mtxErrorCheck or mtxRecursive
99 * protocol: mtxPrioNone or mtxPrioInherit or mtxPrioProtect
100 * robustness: mtxStalled or mtxRobust
101 * prio : mutex priority ceiling; used only with mtxPrioProtect protocol
102 *
103 * Return : mutex object
104 *
105 * Note : for internal use
106 *
107 ******************************************************************************/
108
109#define _MTX_INIT( _mode, _prio ) { _OBJ_INIT(), NULL, _mode, 0, _prio, NULL }
110
111/******************************************************************************
112 *
113 * Name : _VA_MTX
114 *
115 * Description : calculate mutex priority from optional parameter
116 * default: 0
117 *
118 * Note : for internal use
119 *
120 ******************************************************************************/
121
122#define _VA_MTX( _prio ) ( _prio + 0 )
123
135#define OS_MTX( mtx, mode, ... ) \
136 mtx_t mtx[] = { _MTX_INIT(mode, _VA_MTX(__VA_ARGS__) ) }
137
138/** static alias of OS_MTX() */
139#define static_MTX( mtx, mode, ... ) \
140 static mtx_t mtx[] = { _MTX_INIT(mode, _VA_MTX(__VA_ARGS__) ) }
141
155
156#ifndef __cplusplus
157#define MTX_INIT( mode, ... ) \
158 _MTX_INIT( mode, _VA_MTX(__VA_ARGS__) )
159#endif
160
174
175#ifndef __cplusplus
176#define MTX_CREATE( mode, ... ) \
177 { MTX_INIT ( mode, _VA_MTX(__VA_ARGS__) ) }
178/** alias of MTX_CREATE() */
179#define MTX_NEW \
180 MTX_CREATE
181#endif
182
183#ifdef __cplusplus
184extern "C" {
185#endif
186
200void mtx_init( mtx_t *mtx, unsigned mode, unsigned prio );
201
217mtx_t *mtx_create( unsigned mode, unsigned prio );
218
220__STATIC_INLINE
221mtx_t *mtx_new( unsigned mode, unsigned prio ) { return mtx_create(mode, prio); }
222
231void mtx_reset( mtx_t *mtx );
232
234__STATIC_INLINE
235void mtx_kill( mtx_t *mtx ) { mtx_reset(mtx); }
236
245void mtx_destroy( mtx_t *mtx );
246
248__STATIC_INLINE
249void mtx_delete( mtx_t *mtx ) { mtx_destroy(mtx); }
250
261unsigned mtx_prio( mtx_t *mtx );
262
278int mtx_take( mtx_t *mtx );
279
281__STATIC_INLINE
282int mtx_tryLock( mtx_t *mtx ) { return mtx_take(mtx); }
283
304int mtx_waitFor( mtx_t *mtx, cnt_t delay );
305
324int mtx_waitUntil( mtx_t *mtx, cnt_t time );
325
341
342__STATIC_INLINE
343int mtx_wait( mtx_t *mtx ) { return mtx_waitFor(mtx, INFINITE); }
344
346__STATIC_INLINE
347int mtx_lock( mtx_t *mtx ) { return mtx_wait(mtx); }
348
361int mtx_give( mtx_t *mtx );
362
364__STATIC_INLINE
365int mtx_unlock( mtx_t *mtx ) { return mtx_give(mtx); }
366
367#ifdef __cplusplus
368}
369#endif
370
371/* -------------------------------------------------------------------------- */
372
373#if defined(__cplusplus) && (__cplusplus >= 201103L) && !defined(__STATEOS_STDCXX)
374namespace stateos {
375
387struct Mutex : public __mtx
388{
390 constexpr
391 Mutex(): __mtx _MTX_INIT(mtxPrioInherit|mtxErrorCheck, 0) {}
393 constexpr
394 Mutex( const unsigned _mode, const unsigned _prio = 0 ): __mtx _MTX_INIT(_mode, _prio) {}
395
396 ~Mutex() { assert(__mtx::owner == nullptr); }
397
398 /// move constructor
399 Mutex( Mutex&& _src ): __mtx(_src)
400 {
401 assert(_src.owner == nullptr && _src.obj.queue == nullptr);
402 }
403
404 Mutex( const Mutex& ) = delete;
405 Mutex& operator=( Mutex&& ) = delete;
406 Mutex& operator=( const Mutex& ) = delete;
408 void reset () { mtx_reset (this); }
409 void kill () { mtx_kill (this); }
410 void destroy () { mtx_destroy (this); }
411 unsigned prio () { return mtx_prio (this); }
412 int take () { return mtx_take (this); }
413 int tryLock () { return mtx_tryLock (this); }
414 template<typename T>
415 int waitFor ( const T& _delay ) { return mtx_waitFor (this, Clock::count(_delay)); }
416 template<typename T>
417 int waitUntil( const T& _time ) { return mtx_waitUntil(this, Clock::until(_time)); }
418 int wait () { return mtx_wait (this); }
419 int lock () { return mtx_lock (this); }
420 int give () { return mtx_give (this); }
421 int unlock () { return mtx_unlock (this); }
422
423#if __cplusplus >= 201402L
424 using Ptr = std::unique_ptr<Mutex>;
425#else
426 using Ptr = Mutex *;
427#endif
428
442
443 static
444 Ptr Create( const unsigned _mode, const unsigned _prio = 0 )
445 {
446 auto mtx = new (std::nothrow) Mutex(_mode, _prio);
447 if (mtx != nullptr)
448 mtx->__mtx::obj.res = mtx;
449 return Ptr(mtx);
450 }
451
452};
453
458struct LockGuard
459{
461 explicit
462 LockGuard( Mutex& _mtx ): mtx_(&_mtx)
463 {
464 int result = mtx_->lock();
465 assert(result == E_SUCCESS || result == OWNERDEAD || result == E_STOPPED || result == E_DELETED);
466 if (result != E_SUCCESS && result != OWNERDEAD) // OWNERDEAD: the robust mutex is locked, its previous owner has stopped
467 mtx_ = nullptr; // nothing to release
468 }
469
470 ~LockGuard()
471 {
472 if (mtx_ == nullptr)
473 return;
474
475 int result = mtx_->unlock();
476 assert(result == E_SUCCESS);
477 (void) result;
478 }
479
480 /// move constructor
481 LockGuard( LockGuard&& _src ): mtx_(_src.mtx_)
482 {
483 _src.mtx_ = nullptr;
484 }
485
487 bool ownsLock() const { return mtx_ != nullptr; }
488
489 explicit
490 operator bool() const { return ownsLock(); }
491
492 LockGuard( const LockGuard& ) = delete;
493 LockGuard& operator=( LockGuard&& ) = delete;
494 LockGuard& operator=( const LockGuard& ) = delete;
495
496 private:
497 Mutex *mtx_;
498};
499
504struct UniqueLock
505{
507 explicit
508 UniqueLock( Mutex& _mtx ): mtx_(&_mtx), locked_(false)
509 {
510 lock();
511 }
512
514 template<typename T>
515 UniqueLock( Mutex& _mtx, const T& _delay ): mtx_(&_mtx), locked_(false)
516 {
517 waitFor(_delay);
518 }
519
520 /// move constructor
521 UniqueLock( UniqueLock&& _src ): mtx_(_src.mtx_), locked_(_src.locked_)
522 {
523 _src.mtx_ = nullptr;
524 _src.locked_ = false;
525 }
526
528 {
529 unlock();
530 }
531
533 UniqueLock() = default;
534 UniqueLock( const UniqueLock& ) = delete;
535 UniqueLock& operator=( const UniqueLock& ) = delete;
536
537 /// unlock the held mutex and take over the mutex of _src
538 UniqueLock& operator=( UniqueLock&& _src )
539 {
540 unlock();
541
542 mtx_ = _src.mtx_;
543 locked_ = _src.locked_;
544
545 _src.mtx_ = nullptr;
546 _src.locked_ = false;
547
548 return *this;
549 }
550
551 /// try to lock the mutex, don't wait; true: the mutex is locked
552 bool tryLock()
553 {
554 if (mtx_ == nullptr || locked_)
555 return false;
556
557 int result = mtx_->tryLock();
558 assert(result == E_SUCCESS || result == OWNERDEAD || result == E_TIMEOUT);
559 locked_ = result == E_SUCCESS || result == OWNERDEAD;
560 return locked_;
561 }
562
564 template<typename T>
565 bool waitFor( const T& _delay )
566 {
567 if (mtx_ == nullptr || locked_)
568 return false;
569
570 int result = mtx_->waitFor(_delay);
571 assert(result == E_SUCCESS || result == OWNERDEAD || result == E_TIMEOUT || result == E_STOPPED || result == E_DELETED);
572 locked_ = result == E_SUCCESS || result == OWNERDEAD;
573 return locked_;
574 }
575
577 template<typename T>
578 bool waitUntil( const T& _time )
579 {
580 if (mtx_ == nullptr || locked_)
581 return false;
582
583 int result = mtx_->waitUntil(_time);
584 assert(result == E_SUCCESS || result == OWNERDEAD || result == E_TIMEOUT || result == E_STOPPED || result == E_DELETED);
585 locked_ = result == E_SUCCESS || result == OWNERDEAD;
586 return locked_;
587 }
588
589 /// lock the mutex, wait indefinitely; true: the mutex is locked
590 bool lock()
591 {
592 if (mtx_ == nullptr || locked_)
593 return false;
594
595 int result = mtx_->lock();
596 assert(result == E_SUCCESS || result == OWNERDEAD || result == E_STOPPED || result == E_DELETED);
597 locked_ = result == E_SUCCESS || result == OWNERDEAD; // OWNERDEAD: the robust mutex is locked, its previous owner has stopped
598 return locked_;
599 }
600
601 /// unlock the mutex; true: the mutex was unlocked
602 bool unlock()
603 {
604 if (mtx_ == nullptr || !locked_)
605 return false;
606
607 int result = mtx_->unlock();
608 assert(result == E_SUCCESS);
609 locked_ = false;
610 return result == E_SUCCESS;
611 }
612
613 /// true: the mutex is locked by the object
614 bool ownsLock() const
615 {
616 return locked_;
617 }
618
620 explicit
621 operator bool() const
622 {
623 return ownsLock();
624 }
625
626 /// release the mutex without unlocking it, return the mutex
627 Mutex* release()
628 {
629 Mutex* result = mtx_;
630
631 mtx_ = nullptr;
632 locked_ = false;
633
634 return result;
635 }
636
637 /// associated mutex
638 Mutex* mutex() const
639 {
640 return mtx_;
641 }
642
643 private:
644 Mutex *mtx_ = nullptr;
645 bool locked_ = false;
646};
647
648} // namespace
649#endif//__cplusplus
650
651/* -------------------------------------------------------------------------- */
652
654
655#endif//__STATEOS_MTX_H
#define INFINITE
infinite waiting
Definition osbase.h:261
@ E_TIMEOUT
process was released as a result of the end of the timer countdown
Definition osbase.h:150
@ OWNERDEAD
previous owner has stopped
Definition osbase.h:151
@ E_DELETED
process was released as a result of deleting the supervising object
Definition osbase.h:149
@ E_SUCCESS
process was released as a result of taking the supervising object
Definition osbase.h:146
@ E_STOPPED
process was released as a result of reset the supervising object
Definition osbase.h:148
void mtx_delete(mtx_t *mtx)
alias of mtx_destroy()
Definition osmutex.h:248
int mtx_tryLock(mtx_t *mtx)
alias of mtx_take()
Definition osmutex.h:281
mtx_t * mtx_create(unsigned mode, unsigned prio)
create and initialize a new mutex object
unsigned mtx_prio(mtx_t *mtx)
get priority of given mutex
void mtx_reset(mtx_t *mtx)
reset the mutex object and wake up all waiting tasks with 'E_STOPPED' event value
int mtx_give(mtx_t *mtx)
try to unlock the mutex object (only owner task can unlock mutex object), don't wait if the mutex obj...
int mtx_take(mtx_t *mtx)
try to lock the mutex object, don't wait if the mutex object can't be locked immediately
int mtx_lock(mtx_t *mtx)
alias of mtx_wait()
Definition osmutex.h:346
void mtx_kill(mtx_t *mtx)
alias of mtx_reset()
Definition osmutex.h:234
#define mtxErrorCheck
error checking mutex
Definition osmutex.h:48
int mtx_wait(mtx_t *mtx)
try to lock the mutex object, wait indefinitely if the mutex object can't be locked immediately
Definition osmutex.h:342
mtx_t * mtx_new(unsigned mode, unsigned prio)
alias of mtx_create()
Definition osmutex.h:220
int mtx_waitUntil(mtx_t *mtx, cnt_t time)
try to lock the mutex object, wait until given timepoint if the mutex object can't be locked immediat...
int mtx_waitFor(mtx_t *mtx, cnt_t delay)
try to lock the mutex object, wait for given duration of time if the mutex object can't be locked imm...
#define mtxPrioInherit
priority inheritance mutex
Definition osmutex.h:55
int mtx_unlock(mtx_t *mtx)
alias of mtx_give()
Definition osmutex.h:364
void mtx_destroy(mtx_t *mtx)
reset the mutex object, wake up all waiting tasks with 'E_DELETED' event value and free allocated res...
void mtx_init(mtx_t *mtx, unsigned mode, unsigned prio)
initialize a mutex object
static constexpr rep count(const std::chrono::duration< _Rep, _Period > &_delay)
delay in ticks, rounded up to whole ticks; negative delay: IMMEDIATE, delay out of range: INFINITE
Definition osclock.h:109
static constexpr rep until(const std::chrono::time_point< Clock, _Duration > &_time)
time point in ticks, rounded up to whole ticks (only a time point of this clock)
Definition osclock.h:116
create and initialize a lock guard object
Definition osmutex.h:458
LockGuard(Mutex &_mtx)
constructor, see the constructor parameters of the class
Definition osmutex.h:461
bool ownsLock() const
true: the mutex is locked by the guard; false: the mutex was reset or deleted while waiting (or the g...
Definition osmutex.h:486
create and initialize a mutex object
Definition osmutex.h:387
static Ptr Create(const unsigned _mode, const unsigned _prio=0)
create dynamic object with manageable resources
Definition osmutex.h:443
std::unique_ptr< Mutex > Ptr
result type of Create()
Definition osmutex.h:423
int lock()
mtx_lock()
Definition osmutex.h:418
int wait()
mtx_wait()
Definition osmutex.h:417
constexpr Mutex()
constructor, see the constructor parameters of the class
Definition osmutex.h:390
unsigned prio()
mtx_prio()
Definition osmutex.h:410
void kill()
mtx_kill()
Definition osmutex.h:408
int unlock()
mtx_unlock()
Definition osmutex.h:420
int waitFor(const T &_delay)
mtx_waitFor()
Definition osmutex.h:414
int waitUntil(const T &_time)
mtx_waitUntil()
Definition osmutex.h:416
int give()
mtx_give()
Definition osmutex.h:419
void reset()
mtx_reset()
Definition osmutex.h:407
void destroy()
mtx_destroy()
Definition osmutex.h:409
int take()
mtx_take()
Definition osmutex.h:411
int tryLock()
mtx_tryLock()
Definition osmutex.h:412
create and initialize a unique lock object
Definition osmutex.h:504
Mutex * release()
release the mutex without unlocking it, return the mutex
Definition osmutex.h:626
bool waitFor(const T &_delay)
try to lock the mutex, wait for given duration of time; true: the mutex is locked
Definition osmutex.h:564
UniqueLock()=default
default constructor
Mutex * mutex() const
associated mutex
Definition osmutex.h:637
bool tryLock()
try to lock the mutex, don't wait; true: the mutex is locked
Definition osmutex.h:551
bool unlock()
unlock the mutex; true: the mutex was unlocked
Definition osmutex.h:601
bool ownsLock() const
true: the mutex is locked by the object
Definition osmutex.h:613
UniqueLock(Mutex &_mtx)
constructor, see the constructor parameters of the class
Definition osmutex.h:507
bool lock()
lock the mutex, wait indefinitely; true: the mutex is locked
Definition osmutex.h:589
bool waitUntil(const T &_time)
try to lock the mutex, wait until given timepoint; true: the mutex is locked
Definition osmutex.h:577