| 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. |
| 6 | module goroutines |
| 7 | |
| 8 | #include <windows.h> |
| 9 | |
| 10 | fn C.CreateFiber(dwStackSize usize, lpStartAddress voidptr, lpParameter voidptr) voidptr |
| 11 | fn C.ConvertThreadToFiber(lpParameter voidptr) voidptr |
| 12 | fn C.SwitchToFiber(lpFiber voidptr) |
| 13 | fn C.DeleteFiber(lpFiber voidptr) |
| 14 | fn C.ConvertFiberToThread() |
| 15 | |
| 16 | pub struct Context { |
| 17 | pub mut: |
| 18 | uctx voidptr // fiber handle on Windows |
| 19 | is_thread_fiber bool // true if this was created via ConvertThreadToFiber |
| 20 | } |
| 21 | |
| 22 | pub 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 | |
| 27 | pub fn context_switch(mut from Context, to &Context) { |
| 28 | C.SwitchToFiber(to.uctx) |
| 29 | } |
| 30 | |
| 31 | pub 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. |
| 36 | pub 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 | |