From aaa595dbb7cea13cc38344c08b4822a59ced3b7c Mon Sep 17 00:00:00 2001 From: Vftdan Date: Fri, 25 Oct 2024 01:32:21 +0200 Subject: [PATCH] Implement yielding spin lock type --- src/common/util/spin_lock.h | 35 +++++++++++++++++++++++++++++++++++ src/server/main.c | 1 + 2 files changed, 36 insertions(+) create mode 100644 src/common/util/spin_lock.h diff --git a/src/common/util/spin_lock.h b/src/common/util/spin_lock.h new file mode 100644 index 0000000..3b16d5c --- /dev/null +++ b/src/common/util/spin_lock.h @@ -0,0 +1,35 @@ +#ifndef COMMON_UTIL_SPIN_LOCK_H_ +#define COMMON_UTIL_SPIN_LOCK_H_ + +#include "common/util/thread.h" + +#include +#include + +typedef struct { + volatile atomic_flag flag; +} SpinLock; + +HEADER_FN bool +spin_lock_try_acquire(SpinLock *lock) +{ + return !atomic_flag_test_and_set(&lock->flag); +} + +HEADER_FN void +spin_lock_acquire(SpinLock *lock) +{ + int save_errno = errno; + while (!spin_lock_try_acquire(lock)) { + thread_yield(); + } + errno = save_errno; +} + +HEADER_FN void +spin_lock_release(SpinLock *lock) +{ + atomic_flag_clear(&lock->flag); +} + +#endif /* end of include guard: COMMON_UTIL_SPIN_LOCK_H_ */ diff --git a/src/server/main.c b/src/server/main.c index 4daadc4..2b7f76a 100644 --- a/src/server/main.c +++ b/src/server/main.c @@ -4,6 +4,7 @@ #include "common/util/hash_table.h" #include "common/util/byte_serdes.h" #include "common/util/thread.h" +#include "common/util/spin_lock.h" int main(int argc, char **argv)