From a5e3e06306975c8615ca5ab56598cd195da62594 Mon Sep 17 00:00:00 2001 From: Max Wash Date: Sat, 9 Aug 2025 19:49:06 +0100 Subject: [PATCH] core: add basic mutex and per-thread data support --- core/include/blue/core/thread.h | 36 +++++++++++++++++++ core/sys/darwin/thread.c | 61 +++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 core/include/blue/core/thread.h create mode 100644 core/sys/darwin/thread.c diff --git a/core/include/blue/core/thread.h b/core/include/blue/core/thread.h new file mode 100644 index 0000000..6efa9b5 --- /dev/null +++ b/core/include/blue/core/thread.h @@ -0,0 +1,36 @@ +#ifndef BLUELIB_CORE_THREAD_H_ +#define BLUELIB_CORE_THREAD_H_ + +#include +#include +#include + +#if defined(__APPLE__) || defined(__linux__) +#include + +#define B_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER + +typedef pthread_mutex_t b_mutex; +#else +#error Unsupported compiler/system +#endif + +#define B_ONCE_INIT ((b_once)0) + +typedef struct b_thread b_thread; + +typedef int b_once; + +static inline bool b_init_once(b_once *once) +{ + int x = 0; + return b_cmpxchg(once, &x, 1); +} + +BLUE_API b_thread *b_thread_self(void); + +BLUE_API bool b_mutex_lock(b_mutex *mut); +BLUE_API bool b_mutex_trylock(b_mutex *mut); +BLUE_API bool b_mutex_unlock(b_mutex *mut); + +#endif diff --git a/core/sys/darwin/thread.c b/core/sys/darwin/thread.c new file mode 100644 index 0000000..3a5e119 --- /dev/null +++ b/core/sys/darwin/thread.c @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include + +struct b_thread { + pthread_t thr_p; + b_result thr_result; +}; + +static b_once thread_tls_init_once = B_ONCE_INIT; +static pthread_key_t thread_tls_key = {0}; + +static void thread_dtor(void *p) +{ + struct b_thread *thread = p; +} + +static void thread_tls_init() +{ + pthread_key_create(&thread_tls_key, thread_dtor); +} + +struct b_thread *b_thread_self(void) +{ + if (b_init_once(&thread_tls_init_once)) { + thread_tls_init(); + } + + struct b_thread *thread = pthread_getspecific(thread_tls_key); + if (thread) { + return thread; + } + + thread = malloc(sizeof *thread); + assert(thread); + + memset(thread, 0x0, sizeof *thread); + + thread->thr_p = pthread_self(); + + pthread_setspecific(thread_tls_key, thread); + + return thread; +} + +bool b_mutex_lock(b_mutex *mut) +{ + return pthread_mutex_lock(mut) == 0; +} + +bool b_mutex_trylock(b_mutex *mut) +{ + return pthread_mutex_trylock(mut) == 0; +} + +bool b_mutex_unlock(b_mutex *mut) +{ + return pthread_mutex_unlock(mut) == 0; +}