v / vlib / goroutines / atomic_ops.c.v
47 lines · 38 sloc · 1.46 KB · e21acca549c0df34c98beb389088dbf7cee4c4d0
Raw
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.
6module 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
15fn C.goroutines_get_current_m() voidptr
16fn C.goroutines_set_current_m(mp voidptr)
17
18// Typed atomic operations (implemented in tls.c)
19fn C.goroutines_atomic_load_u32(ptr &u32) u32
20fn C.goroutines_atomic_store_u32(ptr &u32, val u32)
21fn C.goroutines_atomic_fetch_add_u32(ptr &u32, val u32) u32
22fn C.goroutines_atomic_fetch_add_i32(ptr &i32, val i32) i32
23fn C.goroutines_atomic_fetch_sub_i32(ptr &i32, val i32) i32
24fn C.goroutines_atomic_fetch_add_u64(ptr &u64, val u64) u64
25fn C.goroutines_atomic_cas_u32(ptr &u32, expected &u32, desired u32) bool
26fn C.goroutines_atomic_cas_ptr(ptr voidptr, expected voidptr, desired voidptr) bool
27
28fn C.grt_spinlock_lock(lk &i32)
29fn C.grt_spinlock_unlock(lk &i32)
30
31fn C.memcpy(dest voidptr, src voidptr, n usize) voidptr
32fn C.memset(dest voidptr, ch int, n usize) voidptr
33fn C.rand() int
34
35// SpinLock - ucontext-safe lock (pthreads mutex breaks with swapcontext).
36pub struct SpinLock {
37mut:
38 state i32
39}
40
41pub fn (mut s SpinLock) acquire() {
42 C.grt_spinlock_lock(&s.state)
43}
44
45pub fn (mut s SpinLock) release() {
46 C.grt_spinlock_unlock(&s.state)
47}
48