diff --git a/README.md b/README.md index 4ff49c97..ae074686 100644 --- a/README.md +++ b/README.md @@ -7436,12 +7436,17 @@ Only one thread shall clear the mutex. Lock the variable mutex for exclusive use. If the mutex is not unlocked, it will wait indefinitely until it is. -The mutex shall not be already locked. + +##### `bool m_mutex_trylock(m_mutex_t mutex)` + +Try to lock the variable mutex for exclusive use. +If the mutex is not unlocked, it will return immediately. +Return true in case of success (mutex locked), false otherwise (mutex unlocked). ##### `void m_mutex_unlock(m_mutex_t mutex)` Unlock the variable mutex for exclusive use. -The mutex shall not be already unlocked. +The mutex shall be locked. #### `m_cond_t` diff --git a/m-thread.h b/m-thread.h index 3a63e0df..4ebb131a 100644 --- a/m-thread.h +++ b/m-thread.h @@ -80,6 +80,12 @@ M_INLINE void m_mutex_lock(m_mutex_t m) mtx_lock(m); } +/* Try to lock the mutex. Return true on success */ +M_INLINE bool m_mutex_trylock(m_mutex_t m) +{ + return mtx_trylock(m) == thrd_success; +} + /* Unlock the mutex */ M_INLINE void m_mutex_unlock(m_mutex_t m) { @@ -242,6 +248,12 @@ M_INLINE void m_mutex_lock(m_mutex_t m) EnterCriticalSection(m); } +/* Try to Lock a mutex. Return true on success */ +M_INLINE bool m_mutex_trylock(m_mutex_t m) +{ + return TryEnterCriticalSection(m) != 0; +} + /* Unlock a mutex */ M_INLINE void m_mutex_unlock(m_mutex_t m) { @@ -390,6 +402,12 @@ M_INLINE void m_mutex_lock(m_mutex_t m) pthread_mutex_lock(m); } +/* Try to Lock a mutex. Return true on success */ +M_INLINE bool m_mutex_trylock(m_mutex_t m) +{ + return pthread_mutex_trylock(m) == 0; +} + /* Unlock the mutex */ M_INLINE void m_mutex_unlock(m_mutex_t m) { @@ -555,6 +573,12 @@ M_INLINE void m_mutex_lock(m_mutex_t m) xSemaphoreTake(m->handle, portMAX_DELAY); } +/* Try to Lock a mutex. Return true on success */ +M_INLINE bool m_mutex_trylock(m_mutex_t m) +{ + return xSemaphoreTake(m->handle, 0) == pdTRUE; +} + /* Unlock the mutex */ M_INLINE void m_mutex_unlock(m_mutex_t m) {