Skip to content

Commit

Permalink
Add m_mutex_trylock function
Browse files Browse the repository at this point in the history
  • Loading branch information
P-p-H-d committed Mar 26, 2024
1 parent a523a97 commit cfab3cf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
24 changes: 24 additions & 0 deletions m-thread.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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)
{
Expand Down

0 comments on commit cfab3cf

Please sign in to comment.