v / vlib / goroutines / context_windows.c.v
41 lines · 34 sloc · 1.29 KB · 0480d0b9a920efc39d5ca3c43509a6cf6ebca274
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// Platform-specific context switching using Windows Fibers.
6module goroutines
7
8#include <windows.h>
9
10fn C.CreateFiber(dwStackSize usize, lpStartAddress voidptr, lpParameter voidptr) voidptr
11fn C.ConvertThreadToFiber(lpParameter voidptr) voidptr
12fn C.SwitchToFiber(lpFiber voidptr)
13fn C.DeleteFiber(lpFiber voidptr)
14fn C.ConvertFiberToThread()
15
16pub struct Context {
17pub mut:
18 uctx voidptr // fiber handle on Windows
19 is_thread_fiber bool // true if this was created via ConvertThreadToFiber
20}
21
22pub fn context_init(mut ctx Context, stack voidptr, stack_size int, entry_fn fn (voidptr), arg voidptr) {
23 // Windows fibers manage their own stack, so we ignore the stack param
24 ctx.uctx = C.CreateFiber(usize(stack_size), voidptr(entry_fn), arg)
25}
26
27pub fn context_switch(mut from Context, to &Context) {
28 C.SwitchToFiber(to.uctx)
29}
30
31pub fn context_set(to &Context) {
32 C.SwitchToFiber(to.uctx)
33}
34
35// convert_thread_to_fiber must be called once per OS thread before using fibers.
36pub fn convert_thread_to_fiber() Context {
37 mut ctx := Context{}
38 ctx.uctx = C.ConvertThreadToFiber(unsafe { nil })
39 ctx.is_thread_fiber = true
40 return ctx
41}
42