From ab0bf7e5dc5f11ef8b108d0b5d65a6013e7fb2f4 Mon Sep 17 00:00:00 2001 From: Ryo Nakamura Date: Thu, 20 Oct 2022 20:25:23 +0900 Subject: add atomic refcnt and locks. It might be unnecessary, if open/close can be done without lock. --- src/atomic.h | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/atomic.h (limited to 'src/atomic.h') diff --git a/src/atomic.h b/src/atomic.h new file mode 100644 index 0000000..a840653 --- /dev/null +++ b/src/atomic.h @@ -0,0 +1,58 @@ +#ifndef _ATOMIC_H_ +#define _ATOMIC_H_ + +#include +#include +#include + +typedef int refcnt; + +static inline void refcnt_inc(refcnt *cnt) +{ + __sync_add_and_fetch(cnt, 1); +} + +static inline void refcnt_dec(refcnt *cnt) +{ + __sync_sub_and_fetch(cnt, 1); +} + + +typedef pthread_mutex_t lock; + +static inline void lock_init(lock *l) +{ + pthread_mutex_init(l, NULL); +} + +static inline void lock_acquire(lock *l) +{ + int ret = pthread_mutex_lock(l); + if (ret < 0) { + switch (ret) { + case EINVAL: + pr_err("invalid mutex\n"); + exit(1); + case EDEADLK: + pr_err("a deadlock would occur\n"); + exit(1); + } + } +} + +static inline void lock_release(lock *l) +{ + int ret = pthread_mutex_unlock(l); + if (ret < 0) { + switch (ret) { + case EINVAL: + pr_err("invalid mutex\n"); + exit(1); + case EPERM: + pr_err("this thread does not hold this mutex\n"); + exit(1); + } + } +} + +#endif /* _ATOMIC_H_ */ -- cgit v1.2.3