| 1 | // Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT license |
| 3 | // that can be found in the LICENSE file. |
| 4 | // |
| 5 | // Atomic operations and C interop for the goroutine scheduler. |
| 6 | module goroutines |
| 7 | |
| 8 | #include <stdlib.h> |
| 9 | #include <string.h> |
| 10 | #include "@VMODROOT/vlib/goroutines/goroutines_tls.h" |
| 11 | |
| 12 | #flag @VMODROOT/vlib/goroutines/tls.c |
| 13 | |
| 14 | // Thread-local storage |
| 15 | fn C.goroutines_get_current_m() voidptr |
| 16 | fn C.goroutines_set_current_m(mp voidptr) |
| 17 | |
| 18 | // Typed atomic operations (implemented in tls.c) |
| 19 | fn C.goroutines_atomic_load_u32(ptr &u32) u32 |
| 20 | fn C.goroutines_atomic_store_u32(ptr &u32, val u32) |
| 21 | fn C.goroutines_atomic_fetch_add_u32(ptr &u32, val u32) u32 |
| 22 | fn C.goroutines_atomic_fetch_add_i32(ptr &i32, val i32) i32 |
| 23 | fn C.goroutines_atomic_fetch_sub_i32(ptr &i32, val i32) i32 |
| 24 | fn C.goroutines_atomic_fetch_add_u64(ptr &u64, val u64) u64 |
| 25 | fn C.goroutines_atomic_cas_u32(ptr &u32, expected &u32, desired u32) bool |
| 26 | fn C.goroutines_atomic_cas_ptr(ptr voidptr, expected voidptr, desired voidptr) bool |
| 27 | |
| 28 | fn C.grt_spinlock_lock(lk &i32) |
| 29 | fn C.grt_spinlock_unlock(lk &i32) |
| 30 | |
| 31 | fn C.memcpy(dest voidptr, src voidptr, n usize) voidptr |
| 32 | fn C.memset(dest voidptr, ch int, n usize) voidptr |
| 33 | fn C.rand() int |
| 34 | |
| 35 | // SpinLock - ucontext-safe lock (pthreads mutex breaks with swapcontext). |
| 36 | pub struct SpinLock { |
| 37 | mut: |
| 38 | state i32 |
| 39 | } |
| 40 | |
| 41 | pub fn (mut s SpinLock) acquire() { |
| 42 | C.grt_spinlock_lock(&s.state) |
| 43 | } |
| 44 | |
| 45 | pub fn (mut s SpinLock) release() { |
| 46 | C.grt_spinlock_unlock(&s.state) |
| 47 | } |
| 48 | |