add initial primitive api for locks

This commit is contained in:
Daan Leijen 2024-06-01 16:45:20 -07:00
parent d9aa19a763
commit 0b3cd51249
11 changed files with 208 additions and 48 deletions

View file

@ -22,7 +22,7 @@ terms of the MIT license. A copy of the license can be found in the file
void _mi_prim_mem_init( mi_os_mem_config_t* config ) {
config->page_size = 64*MI_KiB; // WebAssembly has a fixed page size: 64KiB
config->alloc_granularity = 16;
config->has_overcommit = false;
config->has_overcommit = false;
config->has_partial_free = false;
config->has_virtual_reserve = false;
}
@ -134,7 +134,7 @@ int _mi_prim_alloc(size_t size, size_t try_alignment, bool commit, bool allow_la
//---------------------------------------------
int _mi_prim_commit(void* addr, size_t size, bool* is_zero) {
MI_UNUSED(addr); MI_UNUSED(size);
MI_UNUSED(addr); MI_UNUSED(size);
*is_zero = false;
return 0;
}
@ -199,9 +199,9 @@ mi_msecs_t _mi_prim_clock_now(void) {
// low resolution timer
mi_msecs_t _mi_prim_clock_now(void) {
#if !defined(CLOCKS_PER_SEC) || (CLOCKS_PER_SEC == 1000) || (CLOCKS_PER_SEC == 0)
return (mi_msecs_t)clock();
return (mi_msecs_t)clock();
#elif (CLOCKS_PER_SEC < 1000)
return (mi_msecs_t)clock() * (1000 / (mi_msecs_t)CLOCKS_PER_SEC);
return (mi_msecs_t)clock() * (1000 / (mi_msecs_t)CLOCKS_PER_SEC);
#else
return (mi_msecs_t)clock() / ((mi_msecs_t)CLOCKS_PER_SEC / 1000);
#endif
@ -278,3 +278,43 @@ void _mi_prim_thread_done_auto_done(void) {
void _mi_prim_thread_associate_default_heap(mi_heap_t* heap) {
MI_UNUSED(heap);
}
//----------------------------------------------------------------
// Locks
//----------------------------------------------------------------
#if defined(MI_USE_PTHREADS)
bool _mi_prim_lock(mi_lock_t* lock) {
return (pthread_mutex_lock(lock) == 0);
}
bool _mi_prim_try_lock(mi_lock_t* lock) {
return (pthread_mutex_trylock(lock) == 0);
}
void _mi_prim_unlock(mi_lock_t* lock) {
pthread_mutex_unlock(lock);
}
#else
// fall back to poor man's locks.
bool _mi_prim_lock(mi_lock_t* lock) {
for(int i = 0; i < 1000; i++) { // for at most 1 second?
if (_mi_prim_try_lock(lock)) return true;
mi_atomic_yield(); // this should never happen as wasi is single threaded?
}
return true;
}
bool _mi_prim_try_lock(mi_lock_t* lock) {
uintptr_t expected = 0;
return mi_atomic_cas_strong_acq_rel(lock,&expected,(uintptr_t)1);
}
void _mi_prim_unlock(mi_lock_t* lock) {
mi_atomic_store_release(lock,(uintptr_t)0);
}
#endif