Skip to content

Commit

Permalink
sync: add mutex.try*lock functions for FreeBSD too (#20482)
Browse files Browse the repository at this point in the history
  • Loading branch information
bakul committed Jan 11, 2024
1 parent 0910401 commit 426bcd6
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions vlib/sync/sync_freebsd.c.v
Expand Up @@ -16,6 +16,7 @@ $if !android {
@[trusted]
fn C.pthread_mutex_init(voidptr, voidptr) int
fn C.pthread_mutex_lock(voidptr) int
fn C.pthread_mutex_trylock(voidptr) int
fn C.pthread_mutex_unlock(voidptr) int
fn C.pthread_mutex_destroy(voidptr) int
fn C.pthread_rwlockattr_init(voidptr) int
Expand All @@ -25,6 +26,8 @@ fn C.pthread_rwlockattr_destroy(voidptr) int
fn C.pthread_rwlock_init(voidptr, voidptr) int
fn C.pthread_rwlock_rdlock(voidptr) int
fn C.pthread_rwlock_wrlock(voidptr) int
fn C.pthread_rwlock_tryrdlock(voidptr) int
fn C.pthread_rwlock_trywrlock(voidptr) int
fn C.pthread_rwlock_unlock(voidptr) int
fn C.pthread_rwlock_destroy(voidptr) int
fn C.sem_init(voidptr, int, u32) int
Expand Down Expand Up @@ -101,6 +104,13 @@ pub fn (mut m Mutex) @lock() {
C.pthread_mutex_lock(&m.mutex)
}

// try_lock try to lock the mutex instance and return immediately.
// If the mutex was already locked, it will return false.
@[inline]
pub fn (mut m Mutex) try_lock() bool {
return C.pthread_mutex_trylock(&m.mutex) == 0
}

// unlock unlocks the mutex instance. The mutex is released, and one of
// the other threads, that were blocked, because they called @lock can continue.
@[inline]
Expand Down Expand Up @@ -139,6 +149,20 @@ pub fn (mut m RwMutex) @lock() {
C.pthread_rwlock_wrlock(&m.mutex)
}

// try_rlock try to lock the given RwMutex instance for reading and return immediately.
// If the mutex was already locked, it will return false.
@[inline]
pub fn (mut m RwMutex) try_rlock() bool {
return C.pthread_rwlock_tryrdlock(&m.mutex) == 0
}

// try_wlock try to lock the given RwMutex instance for writing and return immediately.
// If the mutex was already locked, it will return false.
@[inline]
pub fn (mut m RwMutex) try_wlock() bool {
return C.pthread_rwlock_trywrlock(&m.mutex) == 0
}

// destroy frees the resources associated with the rwmutex instance.
// Note: the mutex itself is not freed.
pub fn (mut m RwMutex) destroy() {
Expand Down

0 comments on commit 426bcd6

Please sign in to comment.