Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-base

Source of release 0.44.0

0.44.0 / src / std / thread.lucb

#==============================================================================================
#
#   thread - Native threads
#
#   DESCRIPTION:
#       Spawning, joining and detaching host threads over pthreads, and on Windows over its
#       own threads, with the running thread's identity and yielding and sleeping.
#
#==============================================================================================

from windows_abi import CloseHandle, Sleep
import c
import core
import memory
import platform
import time
import windows_text
extern func pthread_create(thread: void*?*, attributes: void*?, start: func(void*) -> void*?, argument: void*) -> i32
extern func pthread_join(thread: void*, result: void*?*?) -> i32
extern func pthread_detach(thread: void*) -> i32
extern func pthread_self() -> void*
extern func pthread_main_np() -> i32
extern func getpid() -> i32
extern func gettid() -> i32
extern func pthread_attr_init(attributes: void*) -> i32
extern func pthread_attr_setstacksize(attributes: void*, size: usize) -> i32
extern func pthread_attr_destroy(attributes: void*) -> i32
## macOS names the calling thread; Linux names one by handle. Both cap a name at 15 bytes.
extern func mac_setname as "pthread_setname_np"(name: c.str) -> i32
extern func linux_setname as "pthread_setname_np"(thread: void*, name: c.str) -> i32
extern func sched_yield() -> i32
## Windows' threads: a handle each, which joining waits on and closes.
extern func CreateThread(security: void*?, stack: usize, start: func(void*) -> u32, argument: void*, flags: u32, id: u32*?) -> void*?
extern func WaitForSingleObject(handle: void*, milliseconds: u32) -> u32
extern func GetCurrentThread() -> void*
extern func SetThreadDescription(thread: void*, name: const u16*) -> i32
extern func SwitchToThread() -> i32
extern func nanosleep(request: const Duration*, remaining: Duration*?) -> i32

## `struct timespec`: `tv_nsec` is a C `long`, four bytes on Windows.
extern struct Duration:
    seconds: i64
    nanoseconds: c.long

## A thread operation the operating system refused.
# mark: Threads ===============================================================================

## A thread operation failed.
pub let failed: ErrorCode = ErrorCode.package(5)

## `PTHREAD_STACK_MIN`: 16 KiB on macOS and x86-64 glibc; a smaller stack is raised to it.
let least_stack: usize = 16384
## The stack of a thread spawned without a size: 8 MiB on every host, the main thread's
## on Linux, where macOS gives a new thread 512 KiB and Windows 1 MiB. A program may set
## it before it spawns; `spawn(..., stack = n)` overrides it for one thread.
pub var default_stack: usize = 8388608
## The longest name a thread may carry, with its NUL.
let name_room: usize = 16
## What gives a new thread's `local var`s their initialisers (§6.3), run before its entry.
## The native backend's startup sets it when the program has such initialisers, since its
## thread-local storage starts zeroed; under C, `_Thread_local` storage starts initialised
## and it stays none.
pub var locals_start: (func() -> unit)?

## CreateThread's flag that makes its size the stack's reservation, not its first commit.
let stack_reservation: u32 = 0x00010000
## WaitForSingleObject's wait without end, and its answer when the object is signalled.
let wait_forever: u32 = 0xFFFFFFFF
let signalled: u32 = 0

## A running thread; the zero value is no thread at all, so arrays of handles exist. On
## Windows the id is the thread's handle.
pub struct Handle:
    var id: void*?

    ## Wait for the thread to finish.
    pub func join() -> !:
        let id = self.id else error(failed, "no thread to join")
        if platform.windows:
            let waited = WaitForSingleObject(id, wait_forever)
            _ = CloseHandle(id)
            if waited != signalled:
                error(failed, "join")
            return
        if pthread_join(id, none) != 0:
            error(failed, "join")

    ## Let the thread run on its own; its resources are reclaimed at exit.
    pub func detach():
        let id = self.id else return
        if platform.windows:
            _ = CloseHandle(id)
            return
        _ = pthread_detach(id)

## What a new thread starts with: the entry, its context, its name in a heap block of
## `name_room` bytes, NUL-terminated, and the allocator rule of §15.3.
struct Start:
    var entry: func(void*?) -> unit
    var context: void*?
    var name: u8[]
    var name_length: usize

func trampoline(raw: void*) -> void*?:
    let start = (Start*)raw
    if let initialise = locals_start:
        initialise()
    memory.allocator = memory.heap
    let entry = start.entry
    let context = start.context
    if start.name_length > 0:
        let text = (c.str)(str)start.name[..<start.name_length]
        if platform.windows:
            name_windows(text)
        elif platform.macos:
            _ = mac_setname(text)
        else:
            _ = linux_setname(pthread_self(), text)
    release_start(start)
    entry(context)
    return none

## A Windows thread's entry, which answers a status rather than a pointer.
func windows_trampoline(raw: void*) -> u32:
    _ = trampoline(raw)
    return 0

## The calling thread's name, as Windows' tools show it: UTF-16, and best effort.
func name_windows(name: c.str):
    let wide = windows_text.wide(name, failed) catch failure:
        return
    defer free(wide)
    _ = SetThreadDescription(GetCurrentThread(), wide.data)

## Free what `spawn` handed the new thread: the start record and its copy of the name.
func release_start(start: Start*):
    free(start.name) in memory.heap
    free(start) in memory.heap

## Start a thread running `entry(context)`. `stack` is its stack in bytes, `default_stack`
## when 0, at least `PTHREAD_STACK_MIN` and whole pages; `name` is what the host's tools
## show for it, its first fifteen bytes.
pub func spawn(entry: func(void*?) -> unit, context: void*?, stack: usize = 0, name: str = "") -> Handle!:
    let copy = try new u8[name_room] --- in memory.heap
    # on success the thread owns both, and `trampoline` frees them
    errdefer free(copy) in memory.heap
    let kept = name.length if name.length < name_room - 1 else name_room - 1
    memory.copy(copy, name.bytes, kept)
    copy[kept] = 0
    let start = new Start(entry = entry, context = context, name = copy, name_length = kept) in memory.heap catch failure:
        error(memory.exhausted, "memory.exhausted")
    errdefer free(start) in memory.heap
    let wanted = stack if stack > 0 else default_stack
    let page = memory.page_size()
    var size = wanted if wanted > least_stack else least_stack
    size = (size + page - 1) // page * page
    if platform.windows:
        let handle = CreateThread(none, size, windows_trampoline, (void*)start, stack_reservation, none) else error(failed, "spawn")
        return Handle(id = handle)
    var attributes: u64[16]
    if pthread_attr_init((void*)&attributes[0]) != 0:
        error(failed, "spawn")
    if pthread_attr_setstacksize((void*)&attributes[0], size) != 0:
        _ = pthread_attr_destroy((void*)&attributes[0])
        error(failed, "the stack size is refused")
    var id: void*? = none
    let created = pthread_create(&id, (void*)&attributes[0], trampoline, (void*)start)
    _ = pthread_attr_destroy((void*)&attributes[0])
    if created != 0:
        error(failed, "spawn")
    let thread = id else error(failed, "spawn")
    return Handle(id = thread)

## A handle to the calling thread: on Windows its pseudo-handle, which stands for whichever
## thread uses it and which closing leaves alone.
pub func current() -> Handle:
    if platform.windows:
        return Handle(id = GetCurrentThread())
    return Handle(id = pthread_self())

## Whether this is the process's initial thread, for main-thread native resources.
pub func is_main() -> bool:
    if platform.windows:
        return core.on_initial_thread()
    if platform.macos:
        return pthread_main_np() != 0
    if platform.linux:
        return gettid() == getpid()
    return false

## A hint to the processor inside a spin loop.
pub func pause():
    asm arm64:
        yield
    asm x86_64:
        pause

## Yield the processor to another runnable thread.
pub func yield():
    if platform.windows:
        _ = SwitchToThread()
        return
    _ = sched_yield()

## Sleep for at least `milliseconds`: a signal that interrupts the sleep leaves the time
## remaining, which is slept again.
pub func sleep(milliseconds: u64):
    if platform.windows:
        sleep_windows(milliseconds)
        return
    var request = Duration(seconds = (i64)(milliseconds // 1000), nanoseconds = (c.long)((i64)(milliseconds % 1000) * 1000000))
    var remaining = Duration(seconds = 0, nanoseconds = 0)
    while nanosleep(&request, &remaining) != 0 and c.errno() == c.interrupted:
        request = remaining

## Windows rounds waits to clock ticks and may wake before the requested interval.
## Recheck a monotonic deadline without changing system-wide timer resolution. A
## finite chunk also avoids narrowing long durations to Sleep's INFINITE sentinel.
func sleep_windows(milliseconds: u64):
    if milliseconds == 0:
        Sleep(0)
        return
    let longest_finite_wait: u64 = 0xFFFFFFFE
    let start = time.now()
    var elapsed: u64 = 0
    while elapsed < milliseconds:
        let remaining = milliseconds - elapsed
        Sleep((u32)(remaining if remaining < longest_finite_wait else longest_finite_wait))
        elapsed = time.since(start) // 1000000