core: add basic mutex and per-thread data support
This commit is contained in:
36
core/include/blue/core/thread.h
Normal file
36
core/include/blue/core/thread.h
Normal file
@@ -0,0 +1,36 @@
|
||||
#ifndef BLUELIB_CORE_THREAD_H_
|
||||
#define BLUELIB_CORE_THREAD_H_
|
||||
|
||||
#include <blue/core/bitop.h>
|
||||
#include <blue/core/misc.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#if defined(__APPLE__) || defined(__linux__)
|
||||
#include <pthread.h>
|
||||
|
||||
#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
|
||||
61
core/sys/darwin/thread.c
Normal file
61
core/sys/darwin/thread.c
Normal file
@@ -0,0 +1,61 @@
|
||||
#include <assert.h>
|
||||
#include <blue/core/error.h>
|
||||
#include <blue/core/thread.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user