From 426bcd6972b17eef230f04fafee2f34b80f959ee Mon Sep 17 00:00:00 2001 From: Bakul Shah Date: Thu, 11 Jan 2024 01:09:57 -0800 Subject: [PATCH] sync: add mutex.try*lock functions for FreeBSD too (#20482) --- vlib/sync/sync_freebsd.c.v | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/vlib/sync/sync_freebsd.c.v b/vlib/sync/sync_freebsd.c.v index d2f3bcd69a..f8a008dec3 100644 --- a/vlib/sync/sync_freebsd.c.v +++ b/vlib/sync/sync_freebsd.c.v @@ -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 @@ -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 @@ -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] @@ -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() {