Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Private Function

spawn

Private Function
std.Thread.WindowsThreadImpl.spawn
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl

Params

File

Thread.zig:523
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
        const Args = @TypeOf(args);
        const Instance = struct {
            fn_args: Args,
            thread: ThreadCompletion,

            fn entryFn(raw_ptr: windows.PVOID) callconv(.winapi) windows.NTSTATUS {
                const self: *@This() = @ptrCast(@alignCast(raw_ptr));
                defer switch (self.thread.completion.swap(.completed, .seq_cst)) {
                    .running => {},
                    .completed => unreachable,
                    .detached => self.thread.free(),
                };
                return callFn(f, self.fn_args);
            }
        };

        const heap_handle = windows.GetProcessHeap() orelse return error.OutOfMemory;
        const alloc_bytes = @alignOf(Instance) + @sizeOf(Instance);
        const alloc_ptr = windows.ntdll.RtlAllocateHeap(heap_handle, .{}, alloc_bytes) orelse return error.OutOfMemory;
        errdefer assert(windows.ntdll.RtlFreeHeap(heap_handle, .{}, alloc_ptr) != 0);

        const instance_bytes = @as([*]u8, @ptrCast(alloc_ptr))[0..alloc_bytes];
        var fba = std.heap.FixedBufferAllocator.init(instance_bytes);
        const instance = fba.allocator().create(Instance) catch unreachable;
        instance.* = .{
            .fn_args = args,
            .thread = .{
                .completion = Completion.init(.running),
                .heap_ptr = alloc_ptr,
                .heap_handle = heap_handle,
            },
        };

        // Windows appears to only support SYSTEM.BASIC_INFORMATION.AllocationGranularity
        // minimum stack size. Going lower makes it default to that specified in the executable
        // (~1mb). Its also fine if the limit here is incorrect as stack size is only a hint.
        const stack_size = @max(64 * 1024, std.math.lossyCast(u32, config.stack_size));

        // Intended to be equivalent to a kernel32.CreateThread call with no flags set.
        // However, CreateThread is just a wrapper around CreateRemoteThreadEx,
        // so that's the more relevant function in this context.
        //
        // https://github.com/wine-mirror/wine/blob/3d128be6400b3869119d293d0c8fa9e7702978f8/dlls/kernelbase/thread.c#L85
        instance.thread.thread_handle = blk: {
            var active_ctx: ?windows.HANDLE = undefined;
            // Note: Can return null on SUCCESS
            switch (windows.ntdll.RtlGetActiveActivationContext(&active_ctx)) {
                .SUCCESS => {},
                else => |status| return windows.unexpectedStatus(status),
            }
            defer if (active_ctx) |ctx| windows.ntdll.RtlReleaseActivationContext(ctx);

            var teb: *windows.TEB = undefined;
            var attr_list = windows.PS.ATTRIBUTE.LIST{
                .TotalLength = @sizeOf(windows.PS.ATTRIBUTE.LIST),
                .Attributes = .{
                    .{
                        .Attribute = .TEB_ADDRESS,
                        .Size = @sizeOf(*windows.TEB),
                        .u = .{
                            .ValuePtr = @ptrCast(&teb),
                        },
                        .ReturnLength = null,
                    },
                },
            };

            var thread_handle: windows.HANDLE = undefined;
            switch (windows.ntdll.NtCreateThreadEx(
                &thread_handle,
                .{ .MAXIMUM_ALLOWED = true },
                &.{},
                windows.GetCurrentProcess(),
                Instance.entryFn,
                instance,
                .{ .CREATE_SUSPENDED = true },
                0,
                @fromBackingInt(@intCast(stack_size)),
                .default,
                &attr_list,
            )) {
                .SUCCESS => {},
                else => |status| return windows.unexpectedStatus(status),
            }

            if (active_ctx) |ctx| {
                var cookie: windows.ULONG = 0;
                switch (windows.ntdll.RtlActivateActivationContextEx(0, teb, ctx, &cookie)) {
                    .SUCCESS => {},
                    else => |status| return windows.unexpectedStatus(status),
                }
            }

            switch (windows.ntdll.NtResumeThread(thread_handle, null)) {
                .SUCCESS => {},
                else => |status| return windows.unexpectedStatus(status),
            }

            break :blk thread_handle;
        };

        return Impl{ .thread = &instance.thread };
    }