Landin library reference discuss source

hosted/thread/windows.ldn

1--  Starting a thread and waiting for its end on Windows.  `CreateThread`
2--  starts a thread only on a stack the system reserves, so the thread
3--  starts on a small one of the system's, 64 KiB reserved and a page
4--  committed, and switches from there to the stack the group cut from
5--  its backing, as a POSIX thread switches from its start area; the
6--  backing keeps no start area.  The system's stack holds only
7--  `begin_thread`'s frame and the frames kernel32 and ntdll start and end
8--  the thread with.
9
10import core/mem
11import hosted/system
12import platform/windows
13
14fixed if compiler.os == windows then
15    --  The thread's handle, which `join_system_thread` waits on and closes.
16    system_thread: type = struct
17        handle: windows.handle
18    end system_thread
19
20    --  What the system's stack for a thread reserves.
21    start_stack: usize = 65536
22
23    start_alignment: () -> (bytes: usize) =
24        bytes = 16
25    end start_alignment
26
27    start_bytes: () -> (bytes: usize) =
28        bytes = 0
29    end start_bytes
30
31    --  Start a thread that runs `routine` with `argument`, or keep the
32    --  Win32 error the system refused it with in `host`'s cell and fail.
33    --  `area` is empty: the system gives the thread its stack.
34    start_system_thread:
35        (host: system.host, area: []mut u8, record: ptr mut system_thread,
36         routine: windows.thread_routine, argument: usize)
37        -> none ! mem.out_of_memory =
38        _ = lenof area
39        mut id: u32 = 0
40        made: windows.handle = windows.create_thread(
41            0, start_stack, routine, argument,
42            windows.stack_size_is_a_reservation, addr id)
43        if made == windows.no_handle then
44            system.record_errno(host, windows.last_error())
45            fail mem.out_of_memory
46        end if
47        record.val.handle = made
48    end start_system_thread
49
50    --  Wait for the thread `record` describes to end, and close its
51    --  handle.  A wait the system refuses is a defect of this module,
52    --  since only a thread it started is waited for, and once.
53    join_system_thread: (record: ptr mut system_thread) -> none =
54        if windows.wait_for(record.val.handle, windows.infinite)
55          <> windows.wait_object_0
56        then
57            compiler.unreachable()
58        end if
59        _ = windows.close_handle(record.val.handle)
60        record.val.handle = windows.no_handle
61    end join_system_thread
62end if