Implement yielding spin lock type

This commit is contained in:
Vftdan 2024-10-25 01:32:21 +02:00
parent 8dd0ffdb3b
commit aaa595dbb7
2 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,35 @@
#ifndef COMMON_UTIL_SPIN_LOCK_H_
#define COMMON_UTIL_SPIN_LOCK_H_
#include "common/util/thread.h"
#include <stdatomic.h>
#include <errno.h>
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_ */

View File

@ -4,6 +4,7 @@
#include "common/util/hash_table.h" #include "common/util/hash_table.h"
#include "common/util/byte_serdes.h" #include "common/util/byte_serdes.h"
#include "common/util/thread.h" #include "common/util/thread.h"
#include "common/util/spin_lock.h"
int int
main(int argc, char **argv) main(int argc, char **argv)