此结构体表示内核线程。
字段
impl: Impl
Threadbuiltintargetnative_osstdIomathassertposixwindowstestinguse_pthreadsImplmax_name_lenSetNameErrorsetNameGetNameErrorgetNameIdgetCurrentIdCpuCountErrorgetCpuCountSpawnConfigSpawnErrorspawnHandlegetHandledetachjoinYieldErroryieldCompletioncallFnUnsupportedImplWindowsThreadImplPosixThreadImplWasiThreadImplLinuxThreadImpltestThreadNameruntestIncrementNotifytestThreadIdFnxtestTlsmaybeAttachSignalStack
std.Thread.assert
别名
别名目标 std.debug.assert
std.Thread.builtin
常量
std.Thread.callFn
函数
执行与具体实现无关的线程设置(maybeAttachSignalStack),随后
使用 args 调用给定线程入口 f 并处理结果。
fn callFn(comptime f: anytype, args: anytype) switch (Impl) { WindowsThreadImpl => windows.NTSTATUS, LinuxThreadImpl => u8, PosixThreadImpl => ?*anyopaque, else => unreachable, }
std.Thread.Completion
类型
用于同步派生线程与被派生线程分离过程的状态
std.Thread.CpuCountError
错误集合
错误
- PermissionDenied
- SystemResources
- Unexpected
- Unsupported
std.Thread.detach
函数
免除调用方调用 join() 的义务,并让线程在完成时自行清理资源。
调用后,Thread 对象将被消耗;再对其调用任何其他函数都属于未定义行为。
pub fn detach(self: Thread) void
参数
self: Thread
用法示例
test detach {
if (builtin.single_threaded) return error.SkipZigTest;
const io = testing.io;
var value: usize = 0;
var event: Io.Event = .unset;
const thread = try Thread.spawn(.{}, testIncrementNotify, .{ io, &value, &event });
thread.detach();
try event.wait(io);
try std.testing.expectEqual(value, 1);
}
std.Thread.getCpuCount
函数
返回平台报告的可用逻辑 CPU 核心数。
保证返回值 >= 1。
pub fn getCpuCount() CpuCountError!usize
错误
- PermissionDenied
- SystemResources
- Unexpected
- Unsupported
std.Thread.getCurrentId
函数
返回调用线程的平台标识。 尽可能尝试使用线程局部存储,避免系统调用。
pub fn getCurrentId() Id
std.Thread.getHandle
函数
返回此线程的句柄
pub fn getHandle(self: Thread) Handle
参数
self: Thread
std.Thread.getName
函数
在 Windows 上,结果以 WTF-8 编码。 在其他平台上,结果是不指定编码的不透明字节序列。
pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]const u8
参数
self: Thread
buffer_ptr: *[max_name_len:0]u8
错误
- AccessDenied PrctlError
仅可能发生于 PR_SET_SECCOMP/SECCOMP_MODE_FILTER 或 PR_SET_MM/PR_SET_MM_EXE_FILE
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- Canceled Cancelable
调用方请求停止异步操作。
- ConnectionResetByPeer UnendingError
- DeviceBusy OpenError
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput UnendingError
- InvalidAddress PrctlError
- InvalidFileDescriptor PrctlError
仅可与 PR_SET_MM/PR_SET_MM_EXE_FILE 一起出现
- IsDir UnendingError
尝试将目录文件描述符当作普通文件读取。
- LockViolation UnendingError
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForReading UnendingError
打开文件时未授予读取能力。
- OperationUnsupported PrctlError
仅可能随 PR_SET_FP_MODE 出现
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied PrctlError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SocketUnconnected UnendingError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- Unsupported
- UnsupportedFeature PrctlError
仅可能发生于 PR_SET_SPECULATION_CTRL、PR_MPX_ENABLE_MANAGEMENT 或 PR_MPX_DISABLE_MANAGEMENT
- WouldBlock UnendingError
已启用非阻塞模式,且从该文件描述符读取会阻塞。
std.Thread.GetNameError
错误集合
错误
- AccessDenied PrctlError
仅可能发生于 PR_SET_SECCOMP/SECCOMP_MODE_FILTER 或 PR_SET_MM/PR_SET_MM_EXE_FILE
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- Canceled Cancelable
调用方请求停止异步操作。
- ConnectionResetByPeer UnendingError
- DeviceBusy OpenError
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput UnendingError
- InvalidAddress PrctlError
- InvalidFileDescriptor PrctlError
仅可与 PR_SET_MM/PR_SET_MM_EXE_FILE 一起出现
- IsDir UnendingError
尝试将目录文件描述符当作普通文件读取。
- LockViolation UnendingError
由于锁定而无法读取文件。根据
Io实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice OpenError
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForReading UnendingError
打开文件时未授予读取能力。
- OperationUnsupported PrctlError
仅可能随 PR_SET_FP_MODE 出现
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied PrctlError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SocketUnconnected UnendingError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources OpenError
路径超过
max_path_bytes字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- Unsupported
- UnsupportedFeature PrctlError
仅可能发生于 PR_SET_SPECULATION_CTRL、PR_MPX_ENABLE_MANAGEMENT 或 PR_MPX_DISABLE_MANAGEMENT
- WouldBlock UnendingError
已启用非阻塞模式,且从该文件描述符读取会阻塞。
std.Thread.Handle
常量
表示内核线程句柄。 依平台而定,可能为整数或指针。
std.Thread.Id
类型
表示每个线程的 ID,仅保证在单个进程内唯一。
std.Thread.Impl
类型
std.Thread.Io
别名
别名目标 std.Io
std.Thread.join
函数
等待线程完成,再释放 spawn() 时创建的全部资源。
调用后会消耗 Thread 对象;此后对该对象调用任何其他函数均为未定义行为。
pub fn join(self: Thread) void
参数
self: Thread
用法示例
test join {
if (builtin.single_threaded) return error.SkipZigTest;
const io = testing.io;
var value: usize = 0;
var event: Io.Event = .unset;
const thread = try Thread.spawn(.{}, testIncrementNotify, .{ io, &value, &event });
thread.join();
try std.testing.expectEqual(value, 1);
}
std.Thread.LinuxThreadImpl
容器
字段
thread: *ThreadCompletion
std.Thread.LinuxThreadImpl.detach
函数
fn detach(self: Impl) void
参数
self: Impl
std.Thread.LinuxThreadImpl.getCpuCount
函数
fn getCpuCount() !usize
std.Thread.LinuxThreadImpl.getCurrentId
函数
fn getCurrentId() Id
std.Thread.LinuxThreadImpl.getHandle
函数
fn getHandle(self: Impl) ThreadHandle
参数
self: Impl
std.Thread.LinuxThreadImpl.join
函数
fn join(self: Impl) void
参数
self: Impl
std.Thread.LinuxThreadImpl.linux
别名
别名目标 std.os.linux
std.Thread.LinuxThreadImpl.spawn
函数
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl
参数
config: SpawnConfig
std.Thread.LinuxThreadImpl.spawn.entryFn
函数
fn entryFn(raw_arg: usize) callconv(.c) u8
参数
raw_arg: usize
std.Thread.LinuxThreadImpl.ThreadCompletion
容器
字段
completion: Completion = Completion.init(.running)
child_tid: std.atomic.Value(i32) = std.atomic.Value(i32).init(1)
parent_tid: i32 = undefined
mapped: []align(std.heap.page_size_min) u8
std.Thread.LinuxThreadImpl.ThreadCompletion.freeAndExit
函数
调用 munmap(mapped.ptr, mapped.len),再调用 exit(1),期间不触碰位于 mapped.ptr 中的栈。
移植自 musl libc 的 pthread 分离线程实现:
https://github.com/ifduyue/musl/search?q=__unmapself
fn freeAndExit(self: *ThreadCompletion) noreturn
参数
self: *ThreadCompletion
std.Thread.LinuxThreadImpl.ThreadCompletion.sparc_exit_stack
变量
[192]u8
std.Thread.LinuxThreadImpl.ThreadHandle
类型
std.Thread.LinuxThreadImpl.tls_thread_id
变量
?Id
std.Thread.math
别名
别名目标 std.math
std.Thread.max_name_len
常量
std.Thread.maybeAttachSignalStack
函数
配置 std.options.signal_stack_size 请求的每线程备用信号栈。
pub fn maybeAttachSignalStack() void
std.Thread.maybeAttachSignalStack.signal_stack
变量
[size]u8
std.Thread.native_os
常量
std.Thread.posix
别名
别名目标 std.posix
std.Thread.PosixThreadImpl
容器
字段
handle: ThreadHandle
std.Thread.PosixThreadImpl.c
别名
别名目标 std.c
std.Thread.PosixThreadImpl.detach
函数
fn detach(self: Impl) void
参数
self: Impl
std.Thread.PosixThreadImpl.getCpuCount
函数
fn getCpuCount() !usize
std.Thread.PosixThreadImpl.getCurrentId
函数
fn getCurrentId() Id
std.Thread.PosixThreadImpl.getHandle
函数
fn getHandle(self: Impl) ThreadHandle
参数
self: Impl
std.Thread.PosixThreadImpl.join
函数
fn join(self: Impl) void
参数
self: Impl
std.Thread.PosixThreadImpl.spawn
函数
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl
参数
config: SpawnConfig
std.Thread.PosixThreadImpl.spawn.entryFn
函数
fn entryFn(raw_arg: ?*anyopaque) callconv(.c) ?*anyopaque
参数
raw_arg: ?*anyopaque
std.Thread.PosixThreadImpl.ThreadHandle
别名
别名目标 std.c.pthread_t
std.Thread.run
函数
pub fn run(ctx: *@This()) !void
参数
ctx: *@This()
std.Thread.setName
函数
pub fn setName(self: Thread, io: Io, name: []const u8) SetNameError!void
参数
错误
- AccessDenied PrctlError
仅可能发生于 PR_SET_SECCOMP/SECCOMP_MODE_FILTER 或 PR_SET_MM/PR_SET_MM_EXE_FILE
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- BrokenPipe Error
文件为未连接的套接字,或其读取端已关闭。
- Canceled Cancelable
调用方请求停止异步操作。
- DeviceBusy Error
- DiskQuota Error
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput Error
- InvalidAddress PrctlError
- InvalidFileDescriptor PrctlError
仅可与 PR_SET_MM/PR_SET_MM_EXE_FILE 一起出现
- InvalidWtf8
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- LockViolation Error
进程无法访问文件,因为另一进程已锁定 文件的一部分。仅限 Windows。
- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice Error
写入设备期间,若设备在刷新之前或刷新途中断开,就会发生此错误:errno(6),没有此设备或地址。
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForWriting Error
- OperationUnsupported PrctlError
仅可能随 PR_SET_FP_MODE 出现
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied PrctlError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources Error
内核内存不足,无法从 in_fd 读取。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- Unsupported
- UnsupportedFeature PrctlError
仅可能发生于 PR_SET_SPECULATION_CTRL、PR_MPX_ENABLE_MANAGEMENT 或 PR_MPX_DISABLE_MANAGEMENT
- WouldBlock Error
已启用非阻塞模式,而此操作将阻塞。
std.Thread.SetNameError
错误集合
错误
- AccessDenied PrctlError
仅可能发生于 PR_SET_SECCOMP/SECCOMP_MODE_FILTER 或 PR_SET_MM/PR_SET_MM_EXE_FILE
- AntivirusInterference OpenError
Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。
- BadPathName PathNameError
文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。
- BrokenPipe Error
文件为未连接的套接字,或其读取端已关闭。
- Canceled Cancelable
调用方请求停止异步操作。
- DeviceBusy Error
- DiskQuota Error
- FileBusy OpenError
以下三种情况之一:
- pathname 指向正在执行的可执行映像, 且请求写访问。
- pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
- pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
- FileLocksUnsupported OpenError
- FileNotFound OpenError
以下任一情况:
- 某个路径分量不存在。
- 使用了当前工作目录,但该目录已被删除。
- 已打开目录句柄所关联的路径已被删除。
- macOS 上,多个进程或线程将
O.EXCL设为false,并发争相创建同一文件。
- FileTooBig OpenError
文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。
- InputOutput Error
- InvalidAddress PrctlError
- InvalidFileDescriptor PrctlError
仅可与 PR_SET_MM/PR_SET_MM_EXE_FILE 一起出现
- InvalidWtf8
- IsDir OpenError
以下任一情况:
- 路径指向目录,但请求了写权限。
- 路径指向目录,但
allow_directory被设为 false。
- LockViolation Error
进程无法访问文件,因为另一进程已锁定 文件的一部分。仅限 Windows。
- NameTooLong PathNameError
提供的缓冲区过小, 无法容纳路径名时返回。
- NetworkNotFound OpenError
在 Windows 上,未找到
\\server或\\server\share。- NoDevice Error
写入设备期间,若设备在刷新之前或刷新途中断开,就会发生此错误:errno(6),没有此设备或地址。
- NoSpaceLeft OpenError
设备没有空间容纳新文件,无法创建新路径。 仅在提供
CREAT标志时才可能出现此错误。- NotDir OpenError
路径中用作目录的某个部分实际上不是目录, 或者指定了
DIRECTORY,但路径不是目录。- NotOpenForWriting Error
- OperationUnsupported PrctlError
仅可能随 PR_SET_FP_MODE 出现
- PathAlreadyExists OpenError
路径已存在,且提供了
CREAT和EXCL标志。- PermissionDenied PrctlError
- PipeBusy OpenError
- ProcessFdQuotaExceeded OpenError
- ReadOnlyFileSystem OpenError
- SymLinkLoop OpenError
- SystemFdQuotaExceeded OpenError
- SystemResources Error
内核内存不足,无法从 in_fd 读取。
- Unexpected UnexpectedError
操作系统返回了未记录在文档中的错误码。
理论上不可能出现此错误,但处理 此错误优于触发未定义行为。
观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。
- Unsupported
- UnsupportedFeature PrctlError
仅可能发生于 PR_SET_SPECULATION_CTRL、PR_MPX_ENABLE_MANAGEMENT 或 PR_MPX_DISABLE_MANAGEMENT
- WouldBlock Error
已启用非阻塞模式,而此操作将阻塞。
std.Thread.spawn
函数
创建新线程,使用 args 执行 function,并返回新线程的句柄。
config 可向平台提供如何创建和执行 function 的提示。
调用方最终必须调用 join(),等待线程完成并释放其资源,
或调用 detach(),解除调用 join() 的义务,让线程完成时自行清理资源。
pub fn spawn(config: SpawnConfig, comptime function: anytype, args: anytype) SpawnError!Thread
参数
config: SpawnConfig
错误
- LockedMemoryLimitExceeded
已启用
mlockall,创建线程所需的内存将超出限制。- OutOfMemory
用户空间内存不足,无法创建线程。
- SystemResources
内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。
- ThreadQuotaExceeded
触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:
- 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
- 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
- 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
- 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
- Unexpected
std.Thread.SpawnConfig
容器
用于提示如何创建线程的配置选项。
字段
stack_size: usize = default_stack_size线程栈的大小,单位为字节
allocator: ?std.mem.Allocator = null用于为即将派生的线程分配内存的分配器
std.Thread.SpawnConfig.default_stack_size
常量
std.Thread.SpawnError
错误集合
错误
- LockedMemoryLimitExceeded
已启用
mlockall,创建线程所需的内存将超出限制。- OutOfMemory
用户空间内存不足,无法创建线程。
- SystemResources
内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。
- ThreadQuotaExceeded
触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:
- 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
- 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
- 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
- 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
- Unexpected
std.Thread.std
别名
别名目标 std
std.Thread.target
常量
std.Thread.testIncrementNotify
函数
fn testIncrementNotify(io: Io, value: *usize, event: *Io.Event) void
参数
std.Thread.testing
别名
别名目标 std.testing
std.Thread.testThreadIdFn
函数
fn testThreadIdFn(thread_id: *Thread.Id) void
参数
std.Thread.testThreadName
函数
fn testThreadName(io: Io, thread: *Thread) !void
参数
std.Thread.testTls
函数
fn testTls() !void
std.Thread.Thread
别名
别名目标 std.Thread
std.Thread.UnsupportedImpl
命名空间
不能在 Impl switch 语句中产生编译错误,因为它会立即求值。
因此,对于不支持线程的平台,改为在方法自身中产生编译错误。
std.Thread.UnsupportedImpl.detach
函数
fn detach(self: Impl) void
参数
self: Impl
std.Thread.UnsupportedImpl.getCpuCount
函数
fn getCpuCount() !usize
std.Thread.UnsupportedImpl.getCurrentId
函数
fn getCurrentId() usize
std.Thread.UnsupportedImpl.getHandle
函数
fn getHandle(self: Impl) ThreadHandle
参数
self: Impl
std.Thread.UnsupportedImpl.join
函数
fn join(self: Impl) void
参数
self: Impl
std.Thread.UnsupportedImpl.spawn
函数
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl
参数
config: SpawnConfig
std.Thread.UnsupportedImpl.ThreadHandle
类型
std.Thread.UnsupportedImpl.unsupported
函数
fn unsupported(unused: anytype) noreturn
std.Thread.use_pthreads
常量
std.Thread.WasiThreadImpl
容器
字段
thread: *WasiThread
std.Thread.WasiThreadImpl.__get_stack_pointer
函数
返回栈指针的当前值。
inline fn __get_stack_pointer() [*]u8
std.Thread.WasiThreadImpl.__set_stack_pointer
函数
允许设置 WebAssembly 模块中的栈指针。
inline fn __set_stack_pointer(addr: [*]u8) void
参数
addr: [*]u8
std.Thread.WasiThreadImpl.__tls_align
函数
返回 TLS 段的对齐要求
inline fn __tls_align() u32
std.Thread.WasiThreadImpl.__tls_base
函数
返回指向当前线程 TLS 数据段基址的指针。
inline fn __tls_base() [*]u8
std.Thread.WasiThreadImpl.__tls_size
函数
返回 TLS 段的大小
inline fn __tls_size() u32
std.Thread.WasiThreadImpl.__wasm_init_tls
函数
初始化从 memory 开始的 TLS 数据段。
这是由链接器生成的合成函数。
extern fn __wasm_init_tls(memory: [*]u8) void
参数
memory: [*]u8
std.Thread.WasiThreadImpl.@"thread-spawn"
函数
extern "wasi" fn @"thread-spawn"(arg: *Instance) i32
参数
arg: *Instance
std.Thread.WasiThreadImpl.detach
函数
fn detach(self: Impl) void
参数
self: Impl
std.Thread.WasiThreadImpl.getCpuCount
函数
fn getCpuCount() error{Unsupported}!noreturn
错误
- Unsupported
std.Thread.WasiThreadImpl.getCurrentId
函数
fn getCurrentId() Id
std.Thread.WasiThreadImpl.getHandle
函数
fn getHandle(self: Impl) ThreadHandle
参数
self: Impl
std.Thread.WasiThreadImpl.Instance
容器
用于引导线程启动的元数据结构。
字段
thread: WasiThread
tls_offset: usize包含新 __tls_base 的偏移。 偏移从内存基址开始计算。
stack_offset: usize包含新派生线程的栈偏移。 偏移从内存基址开始计算。
raw_ptr: usize包含指向封装对象的原始指针值,该封装对象保存回调的 所有参数。
call_back: *const fn (usize) void指向封装函数的函数指针;线程启动时,封装函数将调用用户 函数。上文提到的指针会作为参数 传递给此函数指针。
original_stack_pointer: [*]u8线程处于 detached 状态时,必须在线程
完成时释放其全部内存。然而,此操作仍在线程内部
执行,因此必须先跳回主线程的栈,
否则会释放当前正在使用的栈。
std.Thread.WasiThreadImpl.join
函数
fn join(self: Impl) void
参数
self: Impl
std.Thread.WasiThreadImpl.spawn
函数
fn spawn(config: std.Thread.SpawnConfig, comptime f: anytype, args: anytype) SpawnError!WasiThreadImpl
参数
config: std.Thread.SpawnConfig
错误
- LockedMemoryLimitExceeded
已启用
mlockall,创建线程所需的内存将超出限制。- OutOfMemory
用户空间内存不足,无法创建线程。
- SystemResources
内核无法分配足够内存,为子进程分配任务结构体, 或复制调用者上下文中必须复制的部分。
- ThreadQuotaExceeded
触及系统施加的线程数量限制。 以下多种限制都可能触发此错误:
- 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
- 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
- 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
- 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
- Unexpected
std.Thread.WasiThreadImpl.spawn.entry
函数
fn entry(ptr: usize) void
参数
ptr: usize
std.Thread.WasiThreadImpl.spawnWasiThread
别名
请求宿主为我们创建新线程。
新线程将调用 wasi_tread_start,传入线程标识
以及提供给 spawnWasiThread 的输入 arg。
std.Thread.WasiThreadImpl.State
类型
std.Thread.WasiThreadImpl.ThreadHandle
类型
std.Thread.WasiThreadImpl.tls_thread_id
变量
Id
std.Thread.WasiThreadImpl.wasi_thread_start
函数
由宿主环境在线程创建后调用。
fn wasi_thread_start(tid: i32, arg: *Instance) callconv(.c) void
参数
tid: i32
arg: *Instance
std.Thread.WasiThreadImpl.WasiThread
容器
字段
std.Thread.windows
别名
别名目标 std.os.windows
std.Thread.WindowsThreadImpl
容器
字段
thread: *ThreadCompletion
std.Thread.WindowsThreadImpl.detach
函数
fn detach(self: Impl) void
参数
self: Impl
std.Thread.WindowsThreadImpl.getCpuCount
函数
fn getCpuCount() !usize
std.Thread.WindowsThreadImpl.getCurrentId
函数
fn getCurrentId() windows.DWORD
std.Thread.WindowsThreadImpl.getHandle
函数
fn getHandle(self: Impl) ThreadHandle
参数
self: Impl
std.Thread.WindowsThreadImpl.join
函数
fn join(self: Impl) void
参数
self: Impl
std.Thread.WindowsThreadImpl.spawn
函数
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl
参数
config: SpawnConfig
std.Thread.WindowsThreadImpl.spawn.entryFn
函数
fn entryFn(raw_ptr: windows.PVOID) callconv(.winapi) windows.NTSTATUS
参数
std.Thread.WindowsThreadImpl.ThreadCompletion
容器
字段
std.Thread.WindowsThreadImpl.ThreadCompletion.free
函数
fn free(self: ThreadCompletion) void
参数
self: ThreadCompletion
std.Thread.WindowsThreadImpl.ThreadHandle
别名
std.Thread.x
变量
i32
std.Thread.yield
函数
当前线程让出执行权,可能允许其他线程运行。
pub fn yield() YieldError!void
错误
- SystemCannotYield
系统未配置为允许让出执行权。
std.Thread.YieldError
错误集合
错误
- SystemCannotYield
系统未配置为允许让出执行权。
源码
std/Thread.zig
//! 此结构体表示内核线程。
const Thread = @This();
const builtin = @import("builtin");
const target = builtin.target;
const native_os = builtin.os.tag;
const std = @import("std.zig");
const Io = std.Io;
const math = std.math;
const assert = std.debug.assert;
const posix = std.posix;
const windows = std.os.windows;
const testing = std.testing;
pub const use_pthreads = native_os != .windows and native_os != .wasi and builtin.link_libc;
const Impl = if (native_os == .windows)
WindowsThreadImpl
else if (use_pthreads)
PosixThreadImpl
else if (native_os == .linux)
LinuxThreadImpl
else if (native_os == .wasi)
WasiThreadImpl
else
UnsupportedImpl;
impl: Impl,
pub const max_name_len = switch (native_os) {
.linux => 15,
.windows => 31,
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => 63,
.netbsd => 31,
.freebsd => 15,
.openbsd => 23,
.dragonfly => 1023,
.illumos => 31,
// https://github.com/SerenityOS/serenity/blob/6b4c300353da49d3508b5442cf61da70bd04d757/Kernel/Tasks/Thread.h#L102
.serenity => 63,
else => 0,
};
pub const SetNameError = error{
NameTooLong,
Unsupported,
Unexpected,
InvalidWtf8,
} || posix.PrctlError || Io.File.Writer.Error || Io.File.OpenError || std.mem.PrintError;
pub fn setName(self: Thread, io: Io, name: []const u8) SetNameError!void {
if (name.len > max_name_len) return error.NameTooLong;
const name_with_terminator = blk: {
var name_buf: [max_name_len:0]u8 = undefined;
@memcpy(name_buf[0..name.len], name);
name_buf[name.len] = 0;
break :blk name_buf[0..name.len :0];
};
switch (native_os) {
.linux => if (use_pthreads) {
if (self.getHandle() == std.c.pthread_self()) {
// 设置调用线程的名称(无需线程 ID)。
assert(try posix.prctl(.SET_NAME, .{@intFromPtr(name_with_terminator.ptr)}) == 0);
return;
} else {
const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return,
.RANGE => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
}
} else {
var buf: [32]u8 = undefined;
const path = try std.mem.print(&buf, "/proc/self/task/{d}/comm", .{self.getHandle()});
const file = try Io.Dir.cwd().openFile(io, path, .{ .mode = .write_only });
defer file.close(io);
try file.writeStreamingAll(io, name);
return;
},
.windows => {
var buf: [max_name_len]u16 = undefined;
switch (windows.ntdll.NtSetInformationThread(
self.getHandle(),
.NameInformation,
&windows.UNICODE_STRING.init(buf[0..try std.unicode.wtf8ToWtf16Le(&buf, name)]),
@sizeOf(windows.UNICODE_STRING),
)) {
.SUCCESS => return,
.NOT_IMPLEMENTED => return error.Unsupported,
else => |err| return windows.unexpectedStatus(err),
}
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => if (use_pthreads) {
// 似乎无法设置任意线程的名称,只能设置当前线程的名称。
if (self.getHandle() != std.c.pthread_self()) return error.Unsupported;
const err = std.c.pthread_setname_np(name_with_terminator.ptr);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return,
else => |e| return posix.unexpectedErrno(e),
}
},
.serenity => if (use_pthreads) {
const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return,
.NAMETOOLONG => unreachable,
.SRCH => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
},
.netbsd, .illumos => if (use_pthreads) {
const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr, null);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return,
.INVAL => unreachable,
.SRCH => unreachable,
.NOMEM => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
},
.freebsd, .openbsd => if (use_pthreads) {
// FreeBSD 上使用 pthread_set_name_np,因为 pthread_setname_np 仅在 FreeBSD 12.2+ 可用。
// TODO: 如果可以接受依赖 FreeBSD 12.2+,则考虑调整,
// 因为 pthread_setname_np 可返回错误。
std.c.pthread_set_name_np(self.getHandle(), name_with_terminator.ptr);
return;
},
.dragonfly => if (use_pthreads) {
const err = std.c.pthread_setname_np(self.getHandle(), name_with_terminator.ptr);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return,
.INVAL => unreachable,
.FAULT => unreachable,
.NAMETOOLONG => unreachable, // 已经检查
.SRCH => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
},
else => {},
}
return error.Unsupported;
}
pub const GetNameError = error{
Unsupported,
Unexpected,
} || posix.PrctlError || posix.ReadError || Io.File.OpenError || std.mem.PrintError;
/// 在 Windows 上,结果以 [WTF-8](https://wtf-8.codeberg.page/) 编码。
/// 在其他平台上,结果是不指定编码的不透明字节序列。
pub fn getName(self: Thread, buffer_ptr: *[max_name_len:0]u8) GetNameError!?[]const u8 {
buffer_ptr[max_name_len] = 0;
var buffer: [:0]u8 = buffer_ptr;
switch (native_os) {
.linux => if (use_pthreads) {
if (self.getHandle() == std.c.pthread_self()) {
// 获取调用线程的名称(无需线程 ID)。
assert(try posix.prctl(.GET_NAME, .{@intFromPtr(buffer.ptr)}) == 0);
return std.mem.sliceTo(buffer, 0);
} else {
const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return std.mem.sliceTo(buffer, 0),
.RANGE => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
}
} else {
var buf: [32]u8 = undefined;
const path = try std.mem.print(&buf, "/proc/self/task/{d}/comm", .{self.getHandle()});
const io = std.Options.debug_io;
const file = try Io.Dir.cwd().openFile(io, path, .{});
defer file.close(io);
var file_reader = file.readerStreaming(io, &.{});
const data_len = file_reader.interface.readSliceShort(buffer_ptr[0 .. max_name_len + 1]) catch |err| switch (err) {
error.ReadFailed => return file_reader.err.?,
};
return if (data_len >= 1) buffer[0 .. data_len - 1] else null;
},
.windows => {
const buf_capacity = @sizeOf(windows.UNICODE_STRING) + (@sizeOf(u16) * max_name_len);
var buf: [buf_capacity]u8 align(@alignOf(windows.UNICODE_STRING)) = undefined;
switch (windows.ntdll.NtQueryInformationThread(
self.getHandle(),
.NameInformation,
&buf,
buf_capacity,
null,
)) {
.SUCCESS => {
const string: *const windows.UNICODE_STRING = @ptrCast(&buf);
const len = std.unicode.wtf16LeToWtf8(buffer, string.slice());
return if (len > 0) buffer[0..len] else null;
},
.NOT_IMPLEMENTED => return error.Unsupported,
else => |err| return windows.unexpectedStatus(err),
}
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => if (use_pthreads) {
const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return std.mem.sliceTo(buffer, 0),
.SRCH => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
},
.serenity => if (use_pthreads) {
const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return,
.NAMETOOLONG => unreachable,
.SRCH => unreachable,
.FAULT => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
},
.netbsd, .illumos => if (use_pthreads) {
const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return std.mem.sliceTo(buffer, 0),
.INVAL => unreachable,
.SRCH => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
},
.freebsd, .openbsd => if (use_pthreads) {
// 在 FreeBSD 上使用 pthread_get_name_np,因为 pthread_getname_np 仅在 FreeBSD 12.2+ 可用。
// TODO: 如果可接受依赖 FreeBSD 12.2+,应重新评估,因为 pthread_getname_np 可以返回错误。
std.c.pthread_get_name_np(self.getHandle(), buffer.ptr, max_name_len + 1);
return std.mem.sliceTo(buffer, 0);
},
.dragonfly => if (use_pthreads) {
const err = std.c.pthread_getname_np(self.getHandle(), buffer.ptr, max_name_len + 1);
switch (@as(posix.E, @fromBackingInt(@intCast(err)))) {
.SUCCESS => return std.mem.sliceTo(buffer, 0),
.INVAL => unreachable,
.FAULT => unreachable,
.SRCH => unreachable,
else => |e| return posix.unexpectedErrno(e),
}
},
else => {},
}
return error.Unsupported;
}
/// 表示每个线程的 ID,仅保证在单个进程内唯一。
pub const Id = switch (native_os) {
.linux,
.dragonfly,
.netbsd,
.freebsd,
.openbsd,
.haiku,
.wasi,
.serenity,
=> u32,
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => u64,
.windows => windows.DWORD,
else => usize,
};
/// 返回调用线程的平台标识。
/// 尽可能尝试使用线程局部存储,避免系统调用。
pub fn getCurrentId() Id {
return Impl.getCurrentId();
}
pub const CpuCountError = error{
PermissionDenied,
SystemResources,
Unsupported,
Unexpected,
};
/// 返回平台报告的可用逻辑 CPU 核心数。
///
/// 保证返回值 >= 1。
pub fn getCpuCount() CpuCountError!usize {
return try Impl.getCpuCount();
}
/// 用于提示如何创建线程的配置选项。
pub const SpawnConfig = struct {
// TODO: 通过编译期调用图分析确定栈空间上界。
// https://github.com/ziglang/zig/issues/157
/// 线程栈的大小,单位为字节
stack_size: usize = default_stack_size,
/// 用于为即将派生的线程分配内存的分配器
allocator: ?std.mem.Allocator = null,
pub const default_stack_size = 16 * 1024 * 1024;
};
pub const SpawnError = error{
/// 触及系统施加的线程数量限制。
/// 以下多种限制都可能触发此错误:
/// * 达到 RLIMIT_NPROC 软资源限制,由 setrlimit(2) 设置,用于限制同一真实用户标识下的进程与线程数量。
/// * 达到内核的系统级进程与线程数量限制 /proc/sys/kernel/threads-max,参见 proc(5)。
/// * 达到最大 PID 数量 /proc/sys/kernel/pid_max,参见 proc(5)。
/// * 达到 cgroup“进程数量”(PIDs)控制器施加的 PID 限制 pids.max。
///
///
///
///
///
///
ThreadQuotaExceeded,
/// 内核无法分配足够内存,为子进程分配任务结构体,
/// 或复制调用者上下文中必须复制的部分。
///
SystemResources,
/// 用户空间内存不足,无法创建线程。
OutOfMemory,
/// 已启用 `mlockall`,创建线程所需的内存将超出限制。
///
LockedMemoryLimitExceeded,
Unexpected,
};
/// 创建新线程,使用 `args` 执行 `function`,并返回新线程的句柄。
/// `config` 可向平台提供如何创建和执行 `function` 的提示。
/// 调用方最终必须调用 `join()`,等待线程完成并释放其资源,
/// 或调用 `detach()`,解除调用 `join()` 的义务,让线程完成时自行清理资源。
pub fn spawn(config: SpawnConfig, comptime function: anytype, args: anytype) SpawnError!Thread {
if (builtin.single_threaded) {
@compileError("Cannot spawn thread when building in single-threaded mode");
}
const impl = try Impl.spawn(config, function, args);
return Thread{ .impl = impl };
}
/// 表示内核线程句柄。
/// 依平台而定,可能为整数或指针。
pub const Handle = Impl.ThreadHandle;
/// 返回此线程的句柄
pub fn getHandle(self: Thread) Handle {
return self.impl.getHandle();
}
/// 免除调用方调用 `join()` 的义务,并让线程在完成时自行清理资源。
/// 调用后,Thread 对象将被消耗;再对其调用任何其他函数都属于未定义行为。
pub fn detach(self: Thread) void {
return self.impl.detach();
}
/// 等待线程完成,再释放 `spawn()` 时创建的全部资源。
/// 调用后会消耗 Thread 对象;此后对该对象调用任何其他函数均为未定义行为。
pub fn join(self: Thread) void {
return self.impl.join();
}
pub const YieldError = error{
/// 系统未配置为允许让出执行权。
SystemCannotYield,
};
/// 当前线程让出执行权,可能允许其他线程运行。
pub fn yield() YieldError!void {
if (native_os == .windows) switch (windows.ntdll.NtYieldExecution()) {
.SUCCESS, .NO_YIELD_PERFORMED => return,
else => return error.SystemCannotYield,
};
switch (posix.errno(posix.system.sched_yield())) {
.SUCCESS => return,
.NOSYS => return error.SystemCannotYield,
else => return error.SystemCannotYield,
}
}
/// 用于同步派生线程与被派生线程分离过程的状态
const Completion = std.atomic.Value(enum(if (builtin.zig_backend == .stage2_riscv64) u32 else u8) {
running,
detached,
completed,
});
/// 执行与具体实现无关的线程设置(`maybeAttachSignalStack`),随后
/// 使用 `args` 调用给定线程入口 `f` 并处理结果。
fn callFn(comptime f: anytype, args: anytype) switch (Impl) {
WindowsThreadImpl => windows.NTSTATUS,
LinuxThreadImpl => u8,
PosixThreadImpl => ?*anyopaque,
else => unreachable,
} {
maybeAttachSignalStack();
const default_value = switch (Impl) {
WindowsThreadImpl => .SUCCESS,
LinuxThreadImpl => 0,
PosixThreadImpl => null,
else => unreachable,
};
const bad_fn_ret = "expected return type of startFn to be 'u8', 'noreturn', '!noreturn', 'void', or '!void'";
switch (@typeInfo(@typeInfo(@TypeOf(f)).@"fn".return_type.?)) {
.noreturn => {
@call(.auto, f, args);
},
.void => {
@call(.auto, f, args);
return default_value;
},
.int => |info| {
if (info.bits != 8) {
@compileError(bad_fn_ret);
}
const status = @call(.auto, f, args);
switch (Impl) {
WindowsThreadImpl => return @fromBackingInt(@intCast(status)),
LinuxThreadImpl => return status,
// pthreads 不支持退出状态,忽略该值
PosixThreadImpl => return default_value,
else => unreachable,
}
},
.error_union => |info| {
switch (info.payload) {
void, noreturn => {
@call(.auto, f, args) catch |err| {
std.debug.print("error: {s}\n", .{@errorName(err)});
if (@errorReturnTrace()) |trace| {
std.debug.dumpErrorReturnTrace(trace);
}
};
return default_value;
},
else => {
@compileError(bad_fn_ret);
},
}
},
else => {
@compileError(bad_fn_ret);
},
}
}
/// 不能在 `Impl` switch 语句中产生编译错误,因为它会立即求值。
/// 因此,对于不支持线程的平台,改为在方法自身中产生编译错误。
const UnsupportedImpl = struct {
pub const ThreadHandle = void;
fn getCurrentId() usize {
return unsupported({});
}
fn getCpuCount() !usize {
return unsupported({});
}
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
return unsupported(.{ config, f, args });
}
fn getHandle(self: Impl) ThreadHandle {
return unsupported(self);
}
fn detach(self: Impl) void {
return unsupported(self);
}
fn join(self: Impl) void {
return unsupported(self);
}
fn unsupported(unused: anytype) noreturn {
_ = unused;
@compileError("Unsupported operating system " ++ @tagName(native_os));
}
};
const WindowsThreadImpl = struct {
pub const ThreadHandle = windows.HANDLE;
fn getCurrentId() windows.DWORD {
return windows.GetCurrentThreadId();
}
fn getCpuCount() !usize {
// 比调用 GetSystemInfo() 更快,即使按摊销成本计算也是如此。
return windows.peb().NumberOfProcessors;
}
thread: *ThreadCompletion,
const ThreadCompletion = struct {
completion: Completion,
heap_ptr: windows.PVOID,
heap_handle: *windows.HEAP,
thread_handle: windows.HANDLE = undefined,
fn free(self: ThreadCompletion) void {
const status = windows.ntdll.RtlFreeHeap(self.heap_handle, .{}, self.heap_ptr);
assert(status != 0);
}
};
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 似乎仅支持 SYSTEM.BASIC_INFORMATION.AllocationGranularity
// 作为最小栈大小。设得更小会退回可执行文件指定的默认值(约 1mb)。
// 此处限制不正确也没有关系,因为栈大小只是提示。
const stack_size = @max(64 * 1024, std.math.lossyCast(u32, config.stack_size));
// 意图等同于不设置任何标志的 kernel32.CreateThread 调用。
// 但 CreateThread 只是对 CreateRemoteThreadEx 的封装,
// 因此后者才是此处更相关的函数。
//
// https://github.com/wine-mirror/wine/blob/3d128be6400b3869119d293d0c8fa9e7702978f8/dlls/kernelbase/thread.c#L85
instance.thread.thread_handle = blk: {
var active_ctx: ?windows.HANDLE = undefined;
// 注意:SUCCESS 时也可能返回 null
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 };
}
fn getHandle(self: Impl) ThreadHandle {
return self.thread.thread_handle;
}
fn detach(self: Impl) void {
windows.CloseHandle(self.thread.thread_handle);
switch (self.thread.completion.swap(.detached, .seq_cst)) {
.running => {},
.completed => self.thread.free(),
.detached => unreachable,
}
}
fn join(self: Impl) void {
switch (windows.ntdll.NtWaitForSingleObject(self.thread.thread_handle, .FALSE, null)) {
windows.NTSTATUS.WAIT_0 => {},
else => |status| windows.unexpectedStatus(status) catch unreachable,
}
windows.CloseHandle(self.thread.thread_handle);
assert(self.thread.completion.load(.seq_cst) == .completed);
self.thread.free();
}
};
const PosixThreadImpl = struct {
const c = std.c;
pub const ThreadHandle = c.pthread_t;
fn getCurrentId() Id {
switch (native_os) {
.linux => {
return LinuxThreadImpl.getCurrentId();
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
var thread_id: u64 = undefined;
// 传入 thread=null,以获取当前线程标识。
assert(c.pthread_threadid_np(null, &thread_id) == 0);
return thread_id;
},
.dragonfly => {
return @as(u32, @bitCast(c.lwp_gettid()));
},
.netbsd => {
return @as(u32, @bitCast(c._lwp_self()));
},
.freebsd => {
return @as(u32, @bitCast(c.pthread_getthreadid_np()));
},
.openbsd => {
return @as(u32, @bitCast(c.getthrid()));
},
.haiku => {
return @as(u32, @bitCast(c.find_thread(null)));
},
.serenity => {
return @as(u32, @bitCast(c.pthread_self()));
},
else => {
return @intFromPtr(c.pthread_self());
},
}
}
fn getCpuCount() !usize {
switch (native_os) {
.linux => {
return LinuxThreadImpl.getCpuCount();
},
.emscripten => {
return @as(usize, @intCast(std.os.emscripten.emscripten_num_logical_cores()));
},
.openbsd => {
var count: c_int = undefined;
var count_size: usize = @sizeOf(c_int);
const mib = [_]c_int{ std.c.CTL.HW, std.c.HW.NCPUONLINE };
posix.sysctl(&mib, &count, &count_size, null, 0) catch |err| switch (err) {
error.NameTooLong, error.UnknownName => unreachable,
else => |e| return e,
};
return @as(usize, @intCast(count));
},
.illumos, .serenity => {
// 获取 CPU 数量的“正规”方式是通过 ioctl 查询
// /dev/kstat,并为每个 CPU 遍历一个
// 链表。(illumos)
const rc = c.sysconf(@backingInt(std.c._SC.NPROCESSORS_ONLN));
return switch (posix.errno(rc)) {
.SUCCESS => @as(usize, @intCast(rc)),
else => |err| posix.unexpectedErrno(err),
};
},
.haiku => {
var system_info: std.c.system_info = undefined;
return switch (std.c.get_system_info(&system_info)) {
0 => @as(usize, @intCast(system_info.cpu_count)),
else => error.Unexpected,
};
},
else => {
var count: c_int = undefined;
var count_len: usize = @sizeOf(c_int);
const name = comptime if (target.os.tag.isDarwin()) "hw.logicalcpu" else "hw.ncpu";
switch (posix.errno(posix.system.sysctlbyname(name, &count, &count_len, null, 0))) {
.SUCCESS => return @intCast(count),
.FAULT => unreachable,
.PERM => return error.PermissionDenied,
.NOMEM => return error.SystemResources,
.NOENT => unreachable,
else => |err| return posix.unexpectedErrno(err),
}
},
}
}
handle: ThreadHandle,
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
const Args = @TypeOf(args);
const allocator = std.heap.c_allocator;
const Instance = struct {
fn entryFn(raw_arg: ?*anyopaque) callconv(.c) ?*anyopaque {
const args_ptr: *Args = @ptrCast(@alignCast(raw_arg));
defer allocator.destroy(args_ptr);
return callFn(f, args_ptr.*);
}
};
const args_ptr = try allocator.create(Args);
args_ptr.* = args;
errdefer allocator.destroy(args_ptr);
var attr: c.pthread_attr_t = undefined;
if (c.pthread_attr_init(&attr) != .SUCCESS) return error.SystemResources;
defer assert(c.pthread_attr_destroy(&attr) == .SUCCESS);
// 使用与不依赖 libc 的实现相同的一组参数。
const stack_size = @max(config.stack_size, 16 * 1024);
assert(c.pthread_attr_setstacksize(&attr, stack_size) == .SUCCESS);
assert(c.pthread_attr_setguardsize(&attr, std.heap.pageSize()) == .SUCCESS);
var handle: c.pthread_t = undefined;
switch (c.pthread_create(
&handle,
&attr,
Instance.entryFn,
@ptrCast(args_ptr),
)) {
.SUCCESS => return Impl{ .handle = handle },
.AGAIN => return error.SystemResources,
.PERM => unreachable,
.INVAL => unreachable,
else => |err| return posix.unexpectedErrno(err),
}
}
fn getHandle(self: Impl) ThreadHandle {
return self.handle;
}
fn detach(self: Impl) void {
switch (c.pthread_detach(self.handle)) {
.SUCCESS => {},
.INVAL => unreachable, // 线程句柄不可联结
.SRCH => unreachable, // 线程句柄无效
else => unreachable,
}
}
fn join(self: Impl) void {
switch (c.pthread_join(self.handle, null)) {
.SUCCESS => {},
.INVAL => unreachable, // 线程句柄不可汇合(或另一线程已在等待其汇合)。
.SRCH => unreachable, // 线程句柄无效
.DEADLK => unreachable, // 两个线程尝试互相加入
else => unreachable,
}
}
};
const WasiThreadImpl = struct {
thread: *WasiThread,
pub const ThreadHandle = i32;
threadlocal var tls_thread_id: Id = 0;
const WasiThread = struct {
/// 线程 ID
tid: std.atomic.Value(i32) = std.atomic.Value(i32).init(0),
/// 包含为启动此线程所分配的全部内存,包括:
/// - 保护页
/// - 栈
/// - TLS 段
/// - `Instance`
/// 调用 `join` 时释放全部内存。
memory: []u8,
/// 用于分配该线程内存的分配器;
/// `join` 时也使用它,以确保清理。
allocator: std.mem.Allocator,
/// 线程的当前状态。
state: State = State.init(.running),
};
/// 用于引导线程启动的元数据结构。
const Instance = struct {
thread: WasiThread,
/// 包含新 __tls_base 的偏移。
/// 偏移从内存基址开始计算。
tls_offset: usize,
/// 包含新派生线程的栈偏移。
/// 偏移从内存基址开始计算。
stack_offset: usize,
/// 包含指向封装对象的原始指针值,该封装对象保存回调的
/// 所有参数。
raw_ptr: usize,
/// 指向封装函数的函数指针;线程启动时,封装函数将调用用户
/// 函数。上文提到的指针会作为参数
/// 传递给此函数指针。
call_back: *const fn (usize) void,
/// 线程处于 `detached` 状态时,必须在线程
/// 完成时释放其全部内存。然而,此操作仍在线程内部
/// 执行,因此必须先跳回主线程的栈,
/// 否则会释放当前正在使用的栈。
original_stack_pointer: [*]u8,
};
const State = std.atomic.Value(enum(u8) { running, completed, detached });
fn getCurrentId() Id {
return tls_thread_id;
}
fn getCpuCount() error{Unsupported}!noreturn {
return error.Unsupported;
}
fn getHandle(self: Impl) ThreadHandle {
return self.thread.tid.load(.seq_cst);
}
fn detach(self: Impl) void {
switch (self.thread.state.swap(.detached, .seq_cst)) {
.running => {},
.completed => self.join(),
.detached => unreachable,
}
}
fn join(self: Impl) void {
defer {
// 创建分配器副本,避免释放内存时
// 释放对原始分配器的引用。
var allocator = self.thread.allocator;
allocator.free(self.thread.memory);
}
while (true) {
const tid = self.thread.tid.load(.seq_cst);
if (tid == 0) break;
const result = asm (
\\ local.get %[ptr]
\\ local.get %[expected]
\\ i64.const -1 # infinite
\\ memory.atomic.wait32 0
\\ local.set %[ret]
: [ret] "=r" (-> u32),
: [ptr] "r" (&self.thread.tid.raw),
[expected] "r" (tid),
);
switch (result) {
0 => continue, // 成功
1 => continue, // expected =! loaded
2 => unreachable, // 超时(无限)
else => unreachable,
}
}
}
fn spawn(config: std.Thread.SpawnConfig, comptime f: anytype, args: anytype) SpawnError!WasiThreadImpl {
if (config.allocator == null) {
@panic("an allocator is required to spawn a WASI thread");
}
// 用于保存用户提供函数参数的封装结构体。
const Wrapper = struct {
args: @TypeOf(args),
fn entry(ptr: usize) void {
const w: *@This() = @ptrFromInt(ptr);
const bad_fn_ret = "expected return type of startFn to be 'u8', 'noreturn', 'void', or '!void'";
switch (@typeInfo(@typeInfo(@TypeOf(f)).@"fn".return_type.?)) {
.noreturn, .void => {
@call(.auto, f, w.args);
},
.int => |info| {
if (info.bits != 8) {
@compileError(bad_fn_ret);
}
_ = @call(.auto, f, w.args); // WASI 线程不支持退出状态,忽略该值。
},
.error_union => |info| {
if (info.payload != void) {
@compileError(bad_fn_ret);
}
@call(.auto, f, w.args) catch |err| {
std.debug.print("error: {s}\n", .{@errorName(err)});
if (@errorReturnTrace()) |trace| {
std.debug.dumpErrorReturnTrace(trace);
}
};
},
else => {
@compileError(bad_fn_ret);
},
}
}
};
var stack_offset: usize = undefined;
var tls_offset: usize = undefined;
var wrapper_offset: usize = undefined;
var instance_offset: usize = undefined;
// 计算存储全部线程信息所需分配的字节数,包括:
// - 线程实际使用的栈
// - TLS 段
// - `Instance`:包含如何调用用户函数的信息。
const map_bytes = blk: {
// 起始至少分配一页作为防护页,
// 防止其他线程覆盖新线程。
// 遗憾的是,WebAssembly 没有只读段的概念,
// 因此这仅是尽力而为的保护。
var bytes: usize = std.wasm.page_size;
bytes = std.mem.alignForward(usize, bytes, 16); // 将栈对齐至 16 字节
stack_offset = bytes;
bytes += @max(std.wasm.page_size, config.stack_size);
bytes = std.mem.alignForward(usize, bytes, __tls_align());
tls_offset = bytes;
bytes += __tls_size();
bytes = std.mem.alignForward(usize, bytes, @alignOf(Wrapper));
wrapper_offset = bytes;
bytes += @sizeOf(Wrapper);
bytes = std.mem.alignForward(usize, bytes, @alignOf(Instance));
instance_offset = bytes;
bytes += @sizeOf(Instance);
bytes = std.mem.alignForward(usize, bytes, std.wasm.page_size);
break :blk bytes;
};
// 分配全部元数据所需的内存。
const allocated_memory = try config.allocator.?.alloc(u8, map_bytes);
const wrapper: *Wrapper = @ptrCast(@alignCast(&allocated_memory[wrapper_offset]));
wrapper.* = .{ .args = args };
const instance: *Instance = @ptrCast(@alignCast(&allocated_memory[instance_offset]));
instance.* = .{
.thread = .{ .memory = allocated_memory, .allocator = config.allocator.? },
.tls_offset = tls_offset,
.stack_offset = stack_offset,
.raw_ptr = @intFromPtr(wrapper),
.call_back = &Wrapper.entry,
.original_stack_pointer = __get_stack_pointer(),
};
const tid = spawnWasiThread(instance);
// 规范规定,任何小于 0 的值都表示错误。
// 这些错误值没有明确定义。WASI-Libc 将其视为 EAGAIN。
if (tid < 0) {
return error.SystemResources;
}
instance.thread.tid.store(tid, .seq_cst);
return .{ .thread = &instance.thread };
}
comptime {
if (!builtin.single_threaded) {
@export(&wasi_thread_start, .{ .name = "wasi_thread_start" });
}
}
/// 由宿主环境在线程创建后调用。
fn wasi_thread_start(tid: i32, arg: *Instance) callconv(.c) void {
comptime assert(!builtin.single_threaded);
__set_stack_pointer(arg.thread.memory.ptr + arg.stack_offset);
__wasm_init_tls(arg.thread.memory.ptr + arg.tls_offset);
@atomicStore(u32, &WasiThreadImpl.tls_thread_id, @intCast(tid), .seq_cst);
// 自举完成,调用用户过程。
arg.call_back(arg.raw_ptr);
switch (arg.thread.state.swap(.completed, .seq_cst)) {
.running => {
// 重置线程标识
asm volatile (
\\ local.get %[ptr]
\\ i32.const 0
\\ i32.atomic.store 0
:
: [ptr] "r" (&arg.thread.tid.raw),
);
// 唤醒监听此线程的主线程
asm volatile (
\\ local.get %[ptr]
\\ i32.const 1 # waiters
\\ memory.atomic.notify 0
\\ drop # no need to know the waiters
:
: [ptr] "r" (&arg.thread.tid.raw),
);
},
.completed => unreachable,
.detached => {
// 恢复原始栈指针,以便释放内存,
// 而无需担心将栈释放
__set_stack_pointer(arg.original_stack_pointer);
// 确保使用副本,防止释放分配器引用本身
var allocator = arg.thread.allocator;
allocator.free(arg.thread.memory);
},
}
}
/// 请求宿主为我们创建新线程。
/// 新线程将调用 `wasi_tread_start`,传入线程标识
/// 以及提供给 `spawnWasiThread` 的输入 `arg`。
const spawnWasiThread = @"thread-spawn";
extern "wasi" fn @"thread-spawn"(arg: *Instance) i32;
/// 初始化从 `memory` 开始的 TLS 数据段。
/// 这是由链接器生成的合成函数。
extern fn __wasm_init_tls(memory: [*]u8) void;
/// 返回指向当前线程 TLS 数据段基址的指针。
inline fn __tls_base() [*]u8 {
return asm (
\\ .globaltype __tls_base, i32
\\ global.get __tls_base
\\ local.set %[ret]
: [ret] "=r" (-> [*]u8),
);
}
/// 返回 TLS 段的大小
inline fn __tls_size() u32 {
return asm volatile (
\\ .globaltype __tls_size, i32, immutable
\\ global.get __tls_size
\\ local.set %[ret]
: [ret] "=r" (-> u32),
);
}
/// 返回 TLS 段的对齐要求
inline fn __tls_align() u32 {
return asm (
\\ .globaltype __tls_align, i32, immutable
\\ global.get __tls_align
\\ local.set %[ret]
: [ret] "=r" (-> u32),
);
}
/// 允许设置 WebAssembly 模块中的栈指针。
inline fn __set_stack_pointer(addr: [*]u8) void {
asm volatile (
\\ local.get %[ptr]
\\ global.set __stack_pointer
:
: [ptr] "r" (addr),
);
}
/// 返回栈指针的当前值。
inline fn __get_stack_pointer() [*]u8 {
return asm (
\\ global.get __stack_pointer
\\ local.set %[stack_ptr]
: [stack_ptr] "=r" (-> [*]u8),
);
}
};
const LinuxThreadImpl = struct {
const linux = std.os.linux;
pub const ThreadHandle = i32;
threadlocal var tls_thread_id: ?Id = null;
fn getCurrentId() Id {
return tls_thread_id orelse {
const tid: u32 = @bitCast(linux.gettid());
tls_thread_id = tid;
return tid;
};
}
fn getCpuCount() !usize {
const cpu_set = try posix.sched_getaffinity(0);
return posix.CPU_COUNT(cpu_set);
}
thread: *ThreadCompletion,
const ThreadCompletion = struct {
completion: Completion = Completion.init(.running),
child_tid: std.atomic.Value(i32) = std.atomic.Value(i32).init(1),
parent_tid: i32 = undefined,
mapped: []align(std.heap.page_size_min) u8,
// 在 SPARC 上,内核从系统调用返回时,必须能够从栈恢复当前寄存器窗口。这在 `freeAndExit` 中带来问题,因为栈正在被释放。
// 好在此时不关心传入寄存器和局部寄存器的内容,因此可以直接告诉内核,此未定义的全局缓冲区就是当前栈。
//
//
//
var sparc_exit_stack: [192]u8 align(16) = undefined;
/// 调用 `munmap(mapped.ptr, mapped.len)`,再调用 `exit(1)`,期间不触碰位于 `mapped.ptr` 中的栈。
/// 移植自 musl libc 的 pthread 分离线程实现:
/// https://github.com/ifduyue/musl/search?q=__unmapself
fn freeAndExit(self: *ThreadCompletion) noreturn {
// 如果此处不将 child_tidptr 重置为 null,在线程退出后,
// 内核就会向该地址写入零;该地址位于下方将取消映射的内存块
// 内部。这有时会破坏其他无关并发线程的
// mmap 内存块。
_ = linux.set_tid_address(null);
// 如果在 SYS_munmap 和 SYS_exit 之间收到信号,任何已安装的信号
// 处理器都会因栈已取消映射而立即发生段错误。为避免此情况,
// 必须在进入内联汇编前屏蔽所有信号。
posix.sigprocmask(std.posix.SIG.BLOCK, &std.os.linux.sigfillset(), null);
switch (target.cpu.arch) {
.x86 => asm volatile (
\\ movl $91, %%eax # SYS_munmap
\\ int $128
\\ movl $1, %%eax # SYS_exit
\\ movl $0, %%ebx
\\ int $128
:
: [ptr] "{ebx}" (@intFromPtr(self.mapped.ptr)),
[len] "{ecx}" (self.mapped.len),
),
.x86_64 => asm volatile (switch (target.abi) {
.gnux32, .muslx32, .x32 =>
\\ movl $0x4000000b, %%eax # SYS_munmap
\\ syscall
\\ movl $0x4000003c, %%eax # SYS_exit
\\ xor %%rdi, %%rdi
\\ syscall
,
else =>
\\ movl $11, %%eax # SYS_munmap
\\ syscall
\\ movl $60, %%eax # SYS_exit
\\ xor %%rdi, %%rdi
\\ syscall
,
}
:
: [ptr] "{rdi}" (@intFromPtr(self.mapped.ptr)),
[len] "{rsi}" (self.mapped.len),
),
.arm, .armeb, .thumb, .thumbeb => asm volatile (
\\ mov r7, #91 // SYS_munmap
\\ svc 0
\\ mov r7, #1 // SYS_exit
\\ mov r0, #0
\\ svc 0
:
: [ptr] "{r0}" (@intFromPtr(self.mapped.ptr)),
[len] "{r1}" (self.mapped.len),
),
.aarch64, .aarch64_be => asm volatile (
\\ mov x8, #215 // SYS_munmap
\\ svc 0
\\ mov x8, #93 // SYS_exit
\\ mov x0, #0
\\ svc 0
:
: [ptr] "{x0}" (@intFromPtr(self.mapped.ptr)),
[len] "{x1}" (self.mapped.len),
),
.alpha => asm volatile (
\\ ldi $0, 73 # SYS_munmap
\\ callsys
\\ ldi $0, 1 # SYS_exit
\\ ldi $16, 0
\\ callsys
:
: [ptr] "{$16}" (@intFromPtr(self.mapped.ptr)),
[len] "{$17}" (self.mapped.len),
),
.arc, .arceb => asm volatile (
\\ mov r8, 215 # SYS_munmap
\\ trap_s 0
\\ mov r8, 93 # SYS_exit
\\ mov r0, 0
\\ trap_s 0
:
: [ptr] "{r0}" (@intFromPtr(self.mapped.ptr)),
[len] "{r1}" (self.mapped.len),
),
.hexagon => asm volatile (
\\ r6 = #215 // SYS_munmap
\\ trap0(#1)
\\ r6 = #93 // SYS_exit
\\ r0 = #0
\\ trap0(#1)
:
: [ptr] "{r0}" (@intFromPtr(self.mapped.ptr)),
[len] "{r1}" (self.mapped.len),
),
.hppa => asm volatile (
\\ ble 0x100(%%sr2, %%r0)
\\ ldi 91, %%r20 /* SYS_munmap */
\\ ldi 0, %%r26
\\ ble 0x100(%%sr2, %%r0)
\\ ldi 1, %%r20 /* SYS_exit */
:
: [ptr] "{r26}" (@intFromPtr(self.mapped.ptr)),
[len] "{r25}" (self.mapped.len),
),
.m68k => asm volatile (
\\ move.l #91, %%d0 // SYS_munmap
\\ trap #0
\\ move.l #1, %%d0 // SYS_exit
\\ move.l #0, %%d1
\\ trap #0
:
: [ptr] "{d1}" (@intFromPtr(self.mapped.ptr)),
[len] "{d2}" (self.mapped.len),
),
.microblaze, .microblazeel => asm volatile (
\\ ori r12, r0, 91 # SYS_munmap
\\ brki r14, 0x8
\\ ori r12, r0, 1 # SYS_exit
\\ ori r5, r0, 0
\\ brki r14, 0x8
:
: [ptr] "{r5}" (@intFromPtr(self.mapped.ptr)),
[len] "{r6}" (self.mapped.len),
),
.mips, .mipsel => asm volatile (
\\ li $v0, 4091 # SYS_munmap
\\ syscall
\\ li $v0, 4001 # SYS_exit
\\ li $a0, 0
\\ syscall
:
: [ptr] "{$4}" (@intFromPtr(self.mapped.ptr)),
[len] "{$5}" (self.mapped.len),
),
.mips64, .mips64el => asm volatile (switch (target.abi) {
.gnuabin32, .muslabin32, .abin32 =>
\\ li $v0, 6011 # SYS_munmap
\\ syscall
\\ li $v0, 6058 # SYS_exit
\\ li $a0, 0
\\ syscall
,
else =>
\\ li $v0, 5011 # SYS_munmap
\\ syscall
\\ li $v0, 5058 # SYS_exit
\\ li $a0, 0
\\ syscall
,
}
:
: [ptr] "{$4}" (@intFromPtr(self.mapped.ptr)),
[len] "{$5}" (self.mapped.len),
),
.or1k => asm volatile (
\\ l.ori r11, r0, 215 # SYS_munmap
\\ l.sys 1
\\ l.ori r11, r0, 93 # SYS_exit
\\ l.ori r3, r0, 0
\\ l.sys 1
:
: [ptr] "{r3}" (@intFromPtr(self.mapped.ptr)),
[len] "{r4}" (self.mapped.len),
),
.powerpc, .powerpcle, .powerpc64, .powerpc64le => asm volatile (
\\ li 0, 91 # SYS_munmap
\\ sc
\\ li 0, 1 # SYS_exit
\\ li 3, 0
\\ sc
:
: [ptr] "{r3}" (@intFromPtr(self.mapped.ptr)),
[len] "{r4}" (self.mapped.len),
),
.riscv32, .riscv64 => asm volatile (
\\ li a7, 215 # SYS_munmap
\\ ecall
\\ li a7, 93 # SYS_exit
\\ mv a0, zero
\\ ecall
:
: [ptr] "{a0}" (@intFromPtr(self.mapped.ptr)),
[len] "{a1}" (self.mapped.len),
),
.s390x => asm volatile (
\\ svc 91 # SYS_munmap
\\ lghi %%r2, 0
\\ svc 1 # SYS_exit
:
: [ptr] "{r2}" (@intFromPtr(self.mapped.ptr)),
[len] "{r3}" (self.mapped.len),
),
.sh, .sheb => asm volatile (
\\ mov #91, r3 ! SYS_munmap
\\ trapa #31
\\ or r0, r0
\\ or r0, r0
\\ or r0, r0
\\ or r0, r0
\\ or r0, r0
\\ mov #1, r3 ! SYS_exit
\\ mov #0, r4
\\ trapa #31
\\ or r0, r0
\\ or r0, r0
\\ or r0, r0
\\ or r0, r0
\\ or r0, r0
:
: [ptr] "{r4}" (@intFromPtr(self.mapped.ptr)),
[len] "{r5}" (self.mapped.len),
),
.sparc => asm volatile (
\\ // See sparc64 comments below.
\\ t 0x3 // ST_FLUSH_WINDOWS
\\ mov %%g3, %%sp
\\ mov %%g1, %%o0
\\ mov %%g2, %%o1
\\ mov 73, %%g1 // SYS_munmap
\\ t 0x10
\\ mov 1, %%g1 // SYS_exit
\\ mov 0, %%o0
\\ t 0x10
:
: [ptr] "{g1}" (@intFromPtr(self.mapped.ptr)),
[len] "{g2}" (self.mapped.len),
[stack] "{g3}" (&sparc_exit_stack),
),
.sparc64 => asm volatile (
\\ // Ensure that the kernel only has to flush the current register window.
\\ flushw
\\ // Set up a fake stack for the syscall to restore l/i registers from. Local
\\ // and incoming registers must be treated as effectively garbage past this
\\ // instruction!
\\ sub %%g3, 2047, %%sp
\\ mov %%g1, %%o0
\\ mov %%g2, %%o1
\\ mov 73, %%g1 // SYS_munmap
\\ t 0x6d
\\ mov 1, %%g1 // SYS_exit
\\ mov 0, %%o0
\\ t 0x6d
:
: [ptr] "{g1}" (@intFromPtr(self.mapped.ptr)),
[len] "{g2}" (self.mapped.len),
[stack] "{g3}" (&sparc_exit_stack),
),
.loongarch32, .loongarch64 => asm volatile (
\\ ori $a7, $zero, 215 # SYS_munmap
\\ syscall 0 # call munmap
\\ ori $a0, $zero, 0
\\ ori $a7, $zero, 93 # SYS_exit
\\ syscall 0 # call exit
:
: [ptr] "{r4}" (@intFromPtr(self.mapped.ptr)),
[len] "{r5}" (self.mapped.len),
),
.csky => asm volatile (
\\ movi r7, 215 # SYS_munmap
\\ trap 0
\\ movi r7, 93 # SYS_exit
\\ movi r0, 0
\\ trap 0
:
: [ptr] "{r0}" (@intFromPtr(self.mapped.ptr)),
[len] "{r1}" (self.mapped.len),
),
.xtensa, .xtensaeb => asm volatile (
\\ movi a2, 81 // SYS_munmap
\\ syscall
\\ movi a6, 0
\\ movi a2, 118 // SYS_exit
\\ syscall
:
: [ptr] "{a6}" (@intFromPtr(self.mapped.ptr)),
[len] "{a3}" (self.mapped.len),
),
else => |cpu_arch| @compileError("Unsupported linux arch: " ++ @tagName(cpu_arch)),
}
unreachable;
}
};
fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl {
const page_size = std.heap.pageSize();
const Args = @TypeOf(args);
const Instance = struct {
fn_args: Args,
thread: ThreadCompletion,
fn entryFn(raw_arg: usize) callconv(.c) u8 {
const self = @as(*@This(), @ptrFromInt(raw_arg));
defer switch (self.thread.completion.swap(.completed, .seq_cst)) {
.running => {},
.completed => unreachable,
.detached => self.thread.freeAndExit(),
};
return callFn(f, self.fn_args);
}
};
var guard_offset: usize = undefined;
var stack_offset: usize = undefined;
var tls_offset: usize = undefined;
var instance_offset: usize = undefined;
const map_bytes = blk: {
var bytes: usize = page_size;
guard_offset = bytes;
bytes += @max(page_size, config.stack_size);
bytes = std.mem.alignForward(usize, bytes, page_size);
stack_offset = bytes;
bytes = std.mem.alignForward(usize, bytes, linux.tls.area_desc.alignment);
tls_offset = bytes;
bytes += linux.tls.area_desc.size;
bytes = std.mem.alignForward(usize, bytes, @alignOf(Instance));
instance_offset = bytes;
bytes += @sizeOf(Instance);
bytes = std.mem.alignForward(usize, bytes, page_size);
break :blk bytes;
};
// 映射所有所需内存,但不授予读写权限,
// 以免立即提交整个区域。
// 匿名映射可确保不超出文件描述符限制。
const mapped = posix.mmap(
null,
map_bytes,
.{},
.{ .TYPE = .PRIVATE, .ANONYMOUS = true },
-1,
0,
) catch |err| switch (err) {
error.MemoryMappingNotSupported => unreachable,
error.AccessDenied => unreachable,
error.PermissionDenied => unreachable,
error.ProcessFdQuotaExceeded => unreachable,
error.SystemFdQuotaExceeded => unreachable,
error.MappingAlreadyExists => unreachable,
else => |e| return e,
};
assert(mapped.len >= map_bytes);
errdefer posix.munmap(mapped);
// 将保护页之外的全部内容映射为可读写。
const guarded: []align(std.heap.page_size_min) u8 = @alignCast(mapped[guard_offset..]);
const protection: posix.PROT = .{ .READ = true, .WRITE = true };
switch (posix.errno(posix.system.mprotect(guarded.ptr, guarded.len, protection))) {
.SUCCESS => {},
.NOMEM => return error.OutOfMemory,
else => |err| return posix.unexpectedErrno(err),
}
// 准备 TLS 段,并在 x86 上需要时准备 user_desc 结构体
var tls_ptr = linux.tls.prepareArea(mapped[tls_offset..][0..linux.tls.area_desc.size]);
var user_desc: if (target.cpu.arch == .x86) linux.user_desc else void = undefined;
if (target.cpu.arch == .x86) {
defer tls_ptr = @intFromPtr(&user_desc);
user_desc = .{
.entry_number = linux.tls.area_desc.gdt_entry_number,
.base_addr = tls_ptr,
.limit = 0xfffff,
.flags = .{
.seg_32bit = 1,
.contents = 0, // 数据
.read_exec_only = 0,
.limit_in_pages = 1,
.seg_not_present = 0,
.useable = 1,
},
};
}
const instance: *Instance = @ptrCast(@alignCast(&mapped[instance_offset]));
instance.* = .{
.fn_args = args,
.thread = .{ .mapped = mapped },
};
const flags: u32 = linux.CLONE.THREAD | linux.CLONE.DETACHED |
linux.CLONE.VM | linux.CLONE.FS | linux.CLONE.FILES |
linux.CLONE.PARENT_SETTID | linux.CLONE.CHILD_CLEARTID |
linux.CLONE.SIGHAND | linux.CLONE.SYSVSEM | linux.CLONE.SETTLS;
switch (linux.errno(linux.clone(
Instance.entryFn,
@intFromPtr(&mapped[stack_offset]),
flags,
@intFromPtr(instance),
&instance.thread.parent_tid,
tls_ptr,
&instance.thread.child_tid.raw,
))) {
.SUCCESS => return Impl{ .thread = &instance.thread },
.AGAIN => return error.ThreadQuotaExceeded,
.INVAL => unreachable,
.NOMEM => return error.SystemResources,
.NOSPC => unreachable,
.PERM => unreachable,
.USERS => unreachable,
else => |err| return posix.unexpectedErrno(err),
}
}
fn getHandle(self: Impl) ThreadHandle {
return self.thread.parent_tid;
}
fn detach(self: Impl) void {
switch (self.thread.completion.swap(.detached, .seq_cst)) {
.running => {},
.completed => self.join(),
.detached => unreachable,
}
}
fn join(self: Impl) void {
defer posix.munmap(self.thread.mapped);
while (true) {
const tid = self.thread.child_tid.load(.seq_cst);
if (tid == 0) break;
switch (linux.errno(linux.futex_4arg(
&self.thread.child_tid.raw,
.{ .cmd = .WAIT, .private = false },
@bitCast(tid),
null,
))) {
.SUCCESS => continue,
.INTR => continue,
.AGAIN => continue,
else => unreachable,
}
}
}
};
fn testThreadName(io: Io, thread: *Thread) !void {
const testCases: []const []const u8 = &.{
"mythread",
&@as([max_name_len]u8, @splat('b')),
};
inline for (testCases) |tc| {
try thread.setName(io, tc);
var name_buffer: [max_name_len:0]u8 = undefined;
const name = try thread.getName(&name_buffer);
if (name) |value| {
try std.testing.expectEqual(tc.len, value.len);
try std.testing.expectEqualStrings(tc, value);
}
}
}
test "setName, getName" {
if (builtin.single_threaded) return error.SkipZigTest;
const io = testing.io;
const Context = struct {
start_wait_event: Io.Event = .unset,
test_done_event: Io.Event = .unset,
thread_done_event: Io.Event = .unset,
done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
thread: Thread = undefined,
pub fn run(ctx: *@This()) !void {
// 等待主线程设置上下文中的 thread 字段。
try ctx.start_wait_event.wait(io);
switch (native_os) {
.windows => testThreadName(io, &ctx.thread) catch |err| switch (err) {
error.Unsupported => return error.SkipZigTest,
else => return err,
},
else => try testThreadName(io, &ctx.thread),
}
// 通知测试已完成
ctx.test_done_event.set(io);
// 等待线程正确退出
try ctx.thread_done_event.wait(io);
}
};
var context = Context{};
var thread = try spawn(.{}, Context.run, .{&context});
context.thread = thread;
context.start_wait_event.set(io);
try context.test_done_event.wait(io);
switch (native_os) {
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
const res = thread.setName(io, "foobar");
try std.testing.expectError(error.Unsupported, res);
},
.windows => testThreadName(io, &thread) catch |err| switch (err) {
error.Unsupported => return error.SkipZigTest,
else => return err,
},
else => try testThreadName(io, &thread),
}
context.thread_done_event.set(io);
thread.join();
}
fn testIncrementNotify(io: Io, value: *usize, event: *Io.Event) void {
value.* += 1;
event.set(io);
}
test join {
if (builtin.single_threaded) return error.SkipZigTest;
const io = testing.io;
var value: usize = 0;
var event: Io.Event = .unset;
const thread = try Thread.spawn(.{}, testIncrementNotify, .{ io, &value, &event });
thread.join();
try std.testing.expectEqual(value, 1);
}
test detach {
if (builtin.single_threaded) return error.SkipZigTest;
const io = testing.io;
var value: usize = 0;
var event: Io.Event = .unset;
const thread = try Thread.spawn(.{}, testIncrementNotify, .{ io, &value, &event });
thread.detach();
try event.wait(io);
try std.testing.expectEqual(value, 1);
}
test "Thread.getCpuCount" {
if (native_os == .wasi) return error.SkipZigTest;
const cpu_count = try Thread.getCpuCount();
try std.testing.expect(cpu_count >= 1);
}
fn testThreadIdFn(thread_id: *Thread.Id) void {
thread_id.* = Thread.getCurrentId();
}
test "Thread.getCurrentId" {
if (builtin.single_threaded) return error.SkipZigTest;
var thread_current_id: Thread.Id = undefined;
const thread = try Thread.spawn(.{}, testThreadIdFn, .{&thread_current_id});
thread.join();
try std.testing.expect(Thread.getCurrentId() != thread_current_id);
}
test "thread local storage" {
if (builtin.single_threaded) return error.SkipZigTest;
if (@sizeOf(usize) == 4) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/25498
const thread1 = try Thread.spawn(.{}, testTls, .{});
const thread2 = try Thread.spawn(.{}, testTls, .{});
try testTls();
thread1.join();
thread2.join();
}
threadlocal var x: i32 = 1234;
fn testTls() !void {
if (x != 1234) return error.TlsBadStartValue;
x += 1;
if (x != 1235) return error.TlsBadEndValue;
}
/// 配置 `std.options.signal_stack_size` 请求的每线程备用信号栈。
pub fn maybeAttachSignalStack() void {
const size = std.options.signal_stack_size orelse return;
switch (builtin.target.os.tag) {
// TODO: Windows 向量化异常处理程序始终在主栈上运行,但可使用
// 目标专属内联汇编切换栈指针。
.windows => return,
.wasi => return,
else => {},
}
const global = struct {
threadlocal var signal_stack: [size]u8 = undefined;
};
std.posix.sigaltstack(&.{
.sp = &global.signal_stack,
.flags = 0,
.size = size,
}, null) catch |err| switch (err) {
error.SizeTooSmall => unreachable, // `std.options.signal_stack_size` 必须足以满足目标需求
error.PermissionDenied => unreachable, // 从信号处理程序中调用了 `maybeAttachSignalStack`。
error.Unexpected => unreachable,
};
}