| ... | ... | @@ -8,7 +8,11 @@ |
| 8 | 8 | //! primitives that operate on kernel threads. For concurrency primitives that support |
| 9 | 9 | //! both evented I/O and async I/O, see the respective names in the top level std namespace. |
| 10 | 10 | |
| 11 | | data: Data, |
| 11 | const std = @import("std.zig"); |
| 12 | const os = std.os; |
| 13 | const assert = std.debug.assert; |
| 14 | const target = std.Target.current; |
| 15 | const Atomic = std.atomic.Atomic; |
| 12 | 16 | |
| 13 | 17 | pub const AutoResetEvent = @import("Thread/AutoResetEvent.zig"); |
| 14 | 18 | pub const Futex = @import("Thread/Futex.zig"); |
| ... | ... | @@ -18,117 +22,51 @@ pub const Mutex = @import("Thread/Mutex.zig"); |
| 18 | 22 | pub const Semaphore = @import("Thread/Semaphore.zig"); |
| 19 | 23 | pub const Condition = @import("Thread/Condition.zig"); |
| 20 | 24 | |
| 21 | | pub const use_pthreads = std.Target.current.os.tag != .windows and builtin.link_libc; |
| 25 | pub const spinLoopHint = @compileError("deprecated: use std.atomic.spinLoopHint"); |
| 22 | 26 | |
| 23 | | const Thread = @This(); |
| 24 | | const std = @import("std.zig"); |
| 25 | | const builtin = std.builtin; |
| 26 | | const os = std.os; |
| 27 | | const mem = std.mem; |
| 28 | | const windows = std.os.windows; |
| 29 | | const c = std.c; |
| 30 | | const assert = std.debug.assert; |
| 27 | pub const use_pthreads = target.os.tag != .windows and std.builtin.link_libc; |
| 31 | 28 | |
| 32 | | const bad_startfn_ret = "expected return type of startFn to be 'u8', 'noreturn', 'void', or '!void'"; |
| 29 | const Thread = @This(); |
| 30 | const Impl = if (target.os.tag == .windows) |
| 31 | WindowsThreadImpl |
| 32 | else if (use_pthreads) |
| 33 | PosixThreadImpl |
| 34 | else if (target.os.tag == .linux) |
| 35 | LinuxThreadImpl |
| 36 | else |
| 37 | UnsupportedImpl; |
| 33 | 38 | |
| 34 | | /// Represents a kernel thread handle. |
| 35 | | /// May be an integer or a pointer depending on the platform. |
| 36 | | /// On Linux and POSIX, this is the same as Id. |
| 37 | | pub const Handle = if (use_pthreads) |
| 38 | | c.pthread_t |
| 39 | | else switch (std.Target.current.os.tag) { |
| 40 | | .linux => i32, |
| 41 | | .windows => windows.HANDLE, |
| 42 | | else => void, |
| 43 | | }; |
| 39 | impl: Impl, |
| 44 | 40 | |
| 45 | 41 | /// Represents a unique ID per thread. |
| 46 | | /// May be an integer or pointer depending on the platform. |
| 47 | | /// On Linux and POSIX, this is the same as Handle. |
| 48 | | pub const Id = switch (std.Target.current.os.tag) { |
| 49 | | .windows => windows.DWORD, |
| 50 | | else => Handle, |
| 51 | | }; |
| 42 | pub const Id = u64; |
| 52 | 43 | |
| 53 | | pub const Data = if (use_pthreads) |
| 54 | | struct { |
| 55 | | handle: Thread.Handle, |
| 56 | | memory: []u8, |
| 57 | | } |
| 58 | | else switch (std.Target.current.os.tag) { |
| 59 | | .linux => struct { |
| 60 | | handle: Thread.Handle, |
| 61 | | memory: []align(mem.page_size) u8, |
| 62 | | }, |
| 63 | | .windows => struct { |
| 64 | | handle: Thread.Handle, |
| 65 | | alloc_start: *c_void, |
| 66 | | heap_handle: windows.HANDLE, |
| 67 | | }, |
| 68 | | else => struct {}, |
| 69 | | }; |
| 70 | | |
| 71 | | pub const spinLoopHint = @compileError("deprecated: use std.atomic.spinLoopHint"); |
| 72 | | |
| 73 | | /// Returns the ID of the calling thread. |
| 74 | | /// Makes a syscall every time the function is called. |
| 75 | | /// On Linux and POSIX, this Id is the same as a Handle. |
| 44 | /// Returns the platform ID of the callers thread. |
| 45 | /// Attempts to use thread locals and avoid syscalls when possible. |
| 76 | 46 | pub fn getCurrentId() Id { |
| 77 | | if (use_pthreads) { |
| 78 | | return c.pthread_self(); |
| 79 | | } else return switch (std.Target.current.os.tag) { |
| 80 | | .linux => os.linux.gettid(), |
| 81 | | .windows => windows.kernel32.GetCurrentThreadId(), |
| 82 | | else => @compileError("Unsupported OS"), |
| 83 | | }; |
| 47 | return Impl.getCurrentId(); |
| 84 | 48 | } |
| 85 | 49 | |
| 86 | | /// Returns the handle of this thread. |
| 87 | | /// On Linux and POSIX, this is the same as Id. |
| 88 | | /// On Linux, it is possible that the thread spawned with `spawn` |
| 89 | | /// finishes executing entirely before the clone syscall completes. In this |
| 90 | | /// case, this function will return 0 rather than the no-longer-existing thread's |
| 91 | | /// pid. |
| 92 | | pub fn handle(self: Thread) Handle { |
| 93 | | return self.data.handle; |
| 94 | | } |
| 50 | pub const CpuCountError = error{ |
| 51 | PermissionDenied, |
| 52 | SystemResources, |
| 53 | Unexpected, |
| 54 | }; |
| 95 | 55 | |
| 96 | | pub fn wait(self: *Thread) void { |
| 97 | | if (use_pthreads) { |
| 98 | | const err = c.pthread_join(self.data.handle, null); |
| 99 | | switch (err) { |
| 100 | | 0 => {}, |
| 101 | | os.EINVAL => unreachable, |
| 102 | | os.ESRCH => unreachable, |
| 103 | | os.EDEADLK => unreachable, |
| 104 | | else => unreachable, |
| 105 | | } |
| 106 | | std.heap.c_allocator.free(self.data.memory); |
| 107 | | std.heap.c_allocator.destroy(self); |
| 108 | | } else switch (std.Target.current.os.tag) { |
| 109 | | .linux => { |
| 110 | | while (true) { |
| 111 | | const pid_value = @atomicLoad(i32, &self.data.handle, .SeqCst); |
| 112 | | if (pid_value == 0) break; |
| 113 | | const rc = os.linux.futex_wait(&self.data.handle, os.linux.FUTEX_WAIT, pid_value, null); |
| 114 | | switch (os.linux.getErrno(rc)) { |
| 115 | | 0 => continue, |
| 116 | | os.EINTR => continue, |
| 117 | | os.EAGAIN => continue, |
| 118 | | else => unreachable, |
| 119 | | } |
| 120 | | } |
| 121 | | os.munmap(self.data.memory); |
| 122 | | }, |
| 123 | | .windows => { |
| 124 | | windows.WaitForSingleObjectEx(self.data.handle, windows.INFINITE, false) catch unreachable; |
| 125 | | windows.CloseHandle(self.data.handle); |
| 126 | | windows.HeapFree(self.data.heap_handle, 0, self.data.alloc_start); |
| 127 | | }, |
| 128 | | else => @compileError("Unsupported OS"), |
| 129 | | } |
| 56 | /// Returns the platforms view on the number of logical CPU cores available. |
| 57 | pub fn getCpuCount() CpuCountError!usize { |
| 58 | return Impl.getCpuCount(); |
| 130 | 59 | } |
| 131 | 60 | |
| 61 | /// Configuration options for hints on how to spawn threads. |
| 62 | pub const SpawnConfig = struct { |
| 63 | // TODO compile-time call graph analysis to determine stack upper bound |
| 64 | // https://github.com/ziglang/zig/issues/157 |
| 65 | |
| 66 | /// Size in bytes of the Thread's stack |
| 67 | stack_size: usize = 16 * 1024 * 1024, |
| 68 | }; |
| 69 | |
| 132 | 70 | pub const SpawnError = error{ |
| 133 | 71 | /// A system-imposed limit on the number of threads was encountered. |
| 134 | 72 | /// There are a number of limits that may trigger this error: |
| ... | ... | @@ -159,248 +97,552 @@ pub const SpawnError = error{ |
| 159 | 97 | Unexpected, |
| 160 | 98 | }; |
| 161 | 99 | |
| 162 | | // Given `T`, the type of the thread startFn, extract the expected type for the |
| 163 | | // context parameter. |
| 164 | | fn SpawnContextType(comptime T: type) type { |
| 165 | | const TI = @typeInfo(T); |
| 166 | | if (TI != .Fn) |
| 167 | | @compileError("expected function type, found " ++ @typeName(T)); |
| 100 | /// Spawns a new thread which executes `function` using `args` and returns a handle the spawned thread. |
| 101 | /// `config` can be used as hints to the platform for now to spawn and execute the `function`. |
| 102 | /// The caller must eventually either call `join()` to wait for the thread to finish and free its resources |
| 103 | /// or call `detach()` to excuse the caller from calling `join()` and have the thread clean up its resources on completion`. |
| 104 | pub fn spawn(config: SpawnConfig, comptime function: anytype, args: anytype) SpawnError!Thread { |
| 105 | if (std.builtin.single_threaded) { |
| 106 | @compileError("Cannot spawn thread when building in single-threaded mode"); |
| 107 | } |
| 108 | |
| 109 | const impl = try Impl.spawn(config, function, args); |
| 110 | return Thread{ .impl = impl }; |
| 111 | } |
| 168 | 112 | |
| 169 | | if (TI.Fn.args.len != 1) |
| 170 | | @compileError("expected function with single argument, found " ++ @typeName(T)); |
| 113 | /// Represents a kernel thread handle. |
| 114 | /// May be an integer or a pointer depending on the platform. |
| 115 | pub const Handle = Impl.ThreadHandle; |
| 171 | 116 | |
| 172 | | return TI.Fn.args[0].arg_type orelse |
| 173 | | @compileError("cannot use a generic function as thread startFn"); |
| 117 | /// Retrns the handle of this thread |
| 118 | pub fn getHandle(self: Thread) Handle { |
| 119 | return self.impl.getHandle(); |
| 174 | 120 | } |
| 175 | 121 | |
| 176 | | /// Spawns a new thread executing startFn, returning an handle for it. |
| 177 | | /// Caller must call wait on the returned thread. |
| 178 | | /// The `startFn` function must take a single argument of type T and return a |
| 179 | | /// value of type u8, noreturn, void or !void. |
| 180 | | /// The `context` parameter is of type T and is passed to the spawned thread. |
| 181 | | pub fn spawn(comptime startFn: anytype, context: SpawnContextType(@TypeOf(startFn))) SpawnError!*Thread { |
| 182 | | if (builtin.single_threaded) @compileError("cannot spawn thread when building in single-threaded mode"); |
| 183 | | // TODO compile-time call graph analysis to determine stack upper bound |
| 184 | | // https://github.com/ziglang/zig/issues/157 |
| 185 | | const default_stack_size = 16 * 1024 * 1024; |
| 122 | /// Release the obligation of the caller to call `join()` and have the thread clean up its own resources on completion. |
| 123 | /// Once called, this consumes the Thread object and invoking any other functions on it is considered undefined behavior. |
| 124 | pub fn detach(self: Thread) void { |
| 125 | return self.impl.detach(); |
| 126 | } |
| 186 | 127 | |
| 187 | | const Context = @TypeOf(context); |
| 128 | /// Waits for the thread to complete, then deallocates any resources created on `spawn()`. |
| 129 | /// Once called, this consumes the Thread object and invoking any other functions on it is considered undefined behavior. |
| 130 | pub fn join(self: Thread) void { |
| 131 | return self.impl.join(); |
| 132 | } |
| 188 | 133 | |
| 189 | | if (std.Target.current.os.tag == .windows) { |
| 190 | | const WinThread = struct { |
| 191 | | const OuterContext = struct { |
| 192 | | thread: Thread, |
| 193 | | inner: Context, |
| 194 | | }; |
| 195 | | fn threadMain(raw_arg: windows.LPVOID) callconv(.C) windows.DWORD { |
| 196 | | const arg = if (@sizeOf(Context) == 0) undefined // |
| 197 | | else @ptrCast(*Context, @alignCast(@alignOf(Context), raw_arg)).*; |
| 198 | | |
| 199 | | switch (@typeInfo(@typeInfo(@TypeOf(startFn)).Fn.return_type.?)) { |
| 200 | | .NoReturn => { |
| 201 | | startFn(arg); |
| 202 | | }, |
| 203 | | .Void => { |
| 204 | | startFn(arg); |
| 205 | | return 0; |
| 206 | | }, |
| 207 | | .Int => |info| { |
| 208 | | if (info.bits != 8) { |
| 209 | | @compileError(bad_startfn_ret); |
| 210 | | } |
| 211 | | return startFn(arg); |
| 212 | | }, |
| 213 | | .ErrorUnion => |info| { |
| 214 | | if (info.payload != void) { |
| 215 | | @compileError(bad_startfn_ret); |
| 216 | | } |
| 217 | | startFn(arg) catch |err| { |
| 218 | | std.debug.warn("error: {s}\n", .{@errorName(err)}); |
| 219 | | if (@errorReturnTrace()) |trace| { |
| 220 | | std.debug.dumpStackTrace(trace.*); |
| 221 | | } |
| 222 | | }; |
| 223 | | return 0; |
| 224 | | }, |
| 225 | | else => @compileError(bad_startfn_ret), |
| 134 | /// State to synchronize detachment of spawner thread to spawned thread |
| 135 | const Completion = Atomic(enum(u8) { |
| 136 | running, |
| 137 | detached, |
| 138 | completed, |
| 139 | }); |
| 140 | |
| 141 | /// Used by the Thread implementations to call the spawned function with the arguments. |
| 142 | fn callFn(comptime f: anytype, args: anytype) switch (Impl) { |
| 143 | WindowsThreadImpl => std.os.windows.DWORD, |
| 144 | LinuxThreadImpl => u8, |
| 145 | PosixThreadImpl => ?*c_void, |
| 146 | else => unreachable, |
| 147 | } { |
| 148 | const default_value = if (Impl == PosixThreadImpl) null else 0; |
| 149 | const bad_fn_ret = "expected return type of startFn to be 'u8', 'noreturn', 'void', or '!void'"; |
| 150 | |
| 151 | switch (@typeInfo(@typeInfo(@TypeOf(f)).Fn.return_type.?)) { |
| 152 | .NoReturn => { |
| 153 | @call(.{}, f, args); |
| 154 | }, |
| 155 | .Void => { |
| 156 | @call(.{}, f, args); |
| 157 | return default_value; |
| 158 | }, |
| 159 | .Int => |info| { |
| 160 | if (info.bits != 8) { |
| 161 | @compileError(bad_fn_ret); |
| 162 | } |
| 163 | |
| 164 | const status = @call(.{}, f, args); |
| 165 | if (Impl != PosixThreadImpl) { |
| 166 | return status; |
| 167 | } |
| 168 | |
| 169 | // pthreads don't support exit status, ignore value |
| 170 | _ = status; |
| 171 | return default_value; |
| 172 | }, |
| 173 | .ErrorUnion => |info| { |
| 174 | if (info.payload != void) { |
| 175 | @compileError(bad_fn_ret); |
| 176 | } |
| 177 | |
| 178 | @call(.{}, f, args) catch |err| { |
| 179 | std.debug.warn("error: {s}\n", .{@errorName(err)}); |
| 180 | if (@errorReturnTrace()) |trace| { |
| 181 | std.debug.dumpStackTrace(trace.*); |
| 226 | 182 | } |
| 183 | }; |
| 184 | |
| 185 | return default_value; |
| 186 | }, |
| 187 | else => { |
| 188 | @compileError(bad_fn_ret); |
| 189 | }, |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /// We can't compile error in the `Impl` switch statement as its eagerly evaluated. |
| 194 | /// So instead, we compile-error on the methods themselves for platforms which don't support threads. |
| 195 | const UnsupportedImpl = struct { |
| 196 | pub const ThreadHandle = void; |
| 197 | |
| 198 | fn getCurrentId() u64 { |
| 199 | return unsupported({}); |
| 200 | } |
| 201 | |
| 202 | fn getCpuCount() !usize { |
| 203 | return unsupported({}); |
| 204 | } |
| 205 | |
| 206 | fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl { |
| 207 | return unsupported(.{ config, f, args }); |
| 208 | } |
| 209 | |
| 210 | fn getHandle(self: Impl) ThreadHandle { |
| 211 | return unsupported(self); |
| 212 | } |
| 213 | |
| 214 | fn detach(self: Impl) void { |
| 215 | return unsupported(self); |
| 216 | } |
| 217 | |
| 218 | fn join(self: Impl) void { |
| 219 | return unsupported(self); |
| 220 | } |
| 221 | |
| 222 | fn unsupported(unusued: anytype) noreturn { |
| 223 | @compileLog("Unsupported operating system", target.os.tag); |
| 224 | _ = unusued; |
| 225 | unreachable; |
| 226 | } |
| 227 | }; |
| 228 | |
| 229 | const WindowsThreadImpl = struct { |
| 230 | const windows = os.windows; |
| 231 | |
| 232 | pub const ThreadHandle = windows.HANDLE; |
| 233 | |
| 234 | fn getCurrentId() u64 { |
| 235 | return windows.kernel32.GetCurrentThreadId(); |
| 236 | } |
| 237 | |
| 238 | fn getCpuCount() !usize { |
| 239 | // Faster than calling into GetSystemInfo(), even if amortized. |
| 240 | return windows.peb().NumberOfProcessors; |
| 241 | } |
| 242 | |
| 243 | thread: *ThreadCompletion, |
| 244 | |
| 245 | const ThreadCompletion = struct { |
| 246 | completion: Completion, |
| 247 | heap_ptr: windows.PVOID, |
| 248 | heap_handle: windows.HANDLE, |
| 249 | thread_handle: windows.HANDLE = undefined, |
| 250 | |
| 251 | fn free(self: ThreadCompletion) void { |
| 252 | const status = windows.kernel32.HeapFree(self.heap_handle, 0, self.heap_ptr); |
| 253 | assert(status != 0); |
| 254 | } |
| 255 | }; |
| 256 | |
| 257 | fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl { |
| 258 | const Args = @TypeOf(args); |
| 259 | const Instance = struct { |
| 260 | fn_args: Args, |
| 261 | thread: ThreadCompletion, |
| 262 | |
| 263 | fn entryFn(raw_ptr: windows.PVOID) callconv(.C) windows.DWORD { |
| 264 | const self = @ptrCast(*@This(), @alignCast(@alignOf(@This()), raw_ptr)); |
| 265 | defer switch (self.thread.completion.swap(.completed, .SeqCst)) { |
| 266 | .running => {}, |
| 267 | .completed => unreachable, |
| 268 | .detached => self.thread.free(), |
| 269 | }; |
| 270 | return callFn(f, self.fn_args); |
| 227 | 271 | } |
| 228 | 272 | }; |
| 229 | 273 | |
| 230 | 274 | const heap_handle = windows.kernel32.GetProcessHeap() orelse return error.OutOfMemory; |
| 231 | | const byte_count = @alignOf(WinThread.OuterContext) + @sizeOf(WinThread.OuterContext); |
| 232 | | const bytes_ptr = windows.kernel32.HeapAlloc(heap_handle, 0, byte_count) orelse return error.OutOfMemory; |
| 233 | | errdefer assert(windows.kernel32.HeapFree(heap_handle, 0, bytes_ptr) != 0); |
| 234 | | const bytes = @ptrCast([*]u8, bytes_ptr)[0..byte_count]; |
| 235 | | const outer_context = std.heap.FixedBufferAllocator.init(bytes).allocator.create(WinThread.OuterContext) catch unreachable; |
| 236 | | outer_context.* = WinThread.OuterContext{ |
| 237 | | .thread = Thread{ |
| 238 | | .data = Thread.Data{ |
| 239 | | .heap_handle = heap_handle, |
| 240 | | .alloc_start = bytes_ptr, |
| 241 | | .handle = undefined, |
| 242 | | }, |
| 275 | const alloc_bytes = @alignOf(Instance) + @sizeOf(Instance); |
| 276 | const alloc_ptr = windows.kernel32.HeapAlloc(heap_handle, 0, alloc_bytes) orelse return error.OutOfMemory; |
| 277 | errdefer assert(windows.kernel32.HeapFree(heap_handle, 0, alloc_ptr) != 0); |
| 278 | |
| 279 | const instance_bytes = @ptrCast([*]u8, alloc_ptr)[0..alloc_bytes]; |
| 280 | const instance = std.heap.FixedBufferAllocator.init(instance_bytes).allocator.create(Instance) catch unreachable; |
| 281 | instance.* = .{ |
| 282 | .fn_args = args, |
| 283 | .thread = .{ |
| 284 | .completion = Completion.init(.running), |
| 285 | .heap_ptr = alloc_ptr, |
| 286 | .heap_handle = heap_handle, |
| 243 | 287 | }, |
| 244 | | .inner = context, |
| 245 | 288 | }; |
| 246 | 289 | |
| 247 | | const parameter = if (@sizeOf(Context) == 0) null else @ptrCast(*c_void, &outer_context.inner); |
| 248 | | outer_context.thread.data.handle = windows.kernel32.CreateThread(null, default_stack_size, WinThread.threadMain, parameter, 0, null) orelse { |
| 249 | | switch (windows.kernel32.GetLastError()) { |
| 250 | | else => |err| return windows.unexpectedError(err), |
| 251 | | } |
| 290 | // Windows appears to only support SYSTEM_INFO.dwAllocationGranularity minimum stack size. |
| 291 | // Going lower makes it default to that specified in the executable (~1mb). |
| 292 | // Its also fine if the limit here is incorrect as stack size is only a hint. |
| 293 | var stack_size = std.math.cast(u32, config.stack_size) catch std.math.maxInt(u32); |
| 294 | stack_size = std.math.max(64 * 1024, stack_size); |
| 295 | |
| 296 | instance.thread.thread_handle = windows.kernel32.CreateThread( |
| 297 | null, |
| 298 | stack_size, |
| 299 | Instance.entryFn, |
| 300 | @ptrCast(*c_void, instance), |
| 301 | 0, |
| 302 | null, |
| 303 | ) orelse { |
| 304 | const errno = windows.kernel32.GetLastError(); |
| 305 | return windows.unexpectedError(errno); |
| 252 | 306 | }; |
| 253 | | return &outer_context.thread; |
| 307 | |
| 308 | return Impl{ .thread = &instance.thread }; |
| 254 | 309 | } |
| 255 | 310 | |
| 256 | | const MainFuncs = struct { |
| 257 | | fn linuxThreadMain(ctx_addr: usize) callconv(.C) u8 { |
| 258 | | const arg = if (@sizeOf(Context) == 0) undefined // |
| 259 | | else @intToPtr(*Context, ctx_addr).*; |
| 311 | fn getHandle(self: Impl) ThreadHandle { |
| 312 | return self.thread.thread_handle; |
| 313 | } |
| 260 | 314 | |
| 261 | | switch (@typeInfo(@typeInfo(@TypeOf(startFn)).Fn.return_type.?)) { |
| 262 | | .NoReturn => { |
| 263 | | startFn(arg); |
| 264 | | }, |
| 265 | | .Void => { |
| 266 | | startFn(arg); |
| 267 | | return 0; |
| 268 | | }, |
| 269 | | .Int => |info| { |
| 270 | | if (info.bits != 8) { |
| 271 | | @compileError(bad_startfn_ret); |
| 272 | | } |
| 273 | | return startFn(arg); |
| 274 | | }, |
| 275 | | .ErrorUnion => |info| { |
| 276 | | if (info.payload != void) { |
| 277 | | @compileError(bad_startfn_ret); |
| 278 | | } |
| 279 | | startFn(arg) catch |err| { |
| 280 | | std.debug.warn("error: {s}\n", .{@errorName(err)}); |
| 281 | | if (@errorReturnTrace()) |trace| { |
| 282 | | std.debug.dumpStackTrace(trace.*); |
| 283 | | } |
| 284 | | }; |
| 285 | | return 0; |
| 286 | | }, |
| 287 | | else => @compileError(bad_startfn_ret), |
| 288 | | } |
| 315 | fn detach(self: Impl) void { |
| 316 | windows.CloseHandle(self.thread.thread_handle); |
| 317 | switch (self.thread.completion.swap(.detached, .SeqCst)) { |
| 318 | .running => {}, |
| 319 | .completed => self.thread.free(), |
| 320 | .detached => unreachable, |
| 289 | 321 | } |
| 290 | | fn posixThreadMain(ctx: ?*c_void) callconv(.C) ?*c_void { |
| 291 | | const arg = if (@sizeOf(Context) == 0) undefined // |
| 292 | | else @ptrCast(*Context, @alignCast(@alignOf(Context), ctx)).*; |
| 322 | } |
| 293 | 323 | |
| 294 | | switch (@typeInfo(@typeInfo(@TypeOf(startFn)).Fn.return_type.?)) { |
| 295 | | .NoReturn => { |
| 296 | | startFn(arg); |
| 297 | | }, |
| 298 | | .Void => { |
| 299 | | startFn(arg); |
| 300 | | return null; |
| 301 | | }, |
| 302 | | .Int => |info| { |
| 303 | | if (info.bits != 8) { |
| 304 | | @compileError(bad_startfn_ret); |
| 305 | | } |
| 306 | | // pthreads don't support exit status, ignore value |
| 307 | | _ = startFn(arg); |
| 308 | | return null; |
| 309 | | }, |
| 310 | | .ErrorUnion => |info| { |
| 311 | | if (info.payload != void) { |
| 312 | | @compileError(bad_startfn_ret); |
| 313 | | } |
| 314 | | startFn(arg) catch |err| { |
| 315 | | std.debug.warn("error: {s}\n", .{@errorName(err)}); |
| 316 | | if (@errorReturnTrace()) |trace| { |
| 317 | | std.debug.dumpStackTrace(trace.*); |
| 318 | | } |
| 319 | | }; |
| 320 | | return null; |
| 321 | | }, |
| 322 | | else => @compileError(bad_startfn_ret), |
| 323 | | } |
| 324 | fn join(self: Impl) void { |
| 325 | windows.WaitForSingleObjectEx(self.thread.thread_handle, windows.INFINITE, false) catch unreachable; |
| 326 | windows.CloseHandle(self.thread.thread_handle); |
| 327 | assert(self.thread.completion.load(.SeqCst) == .completed); |
| 328 | self.thread.free(); |
| 329 | } |
| 330 | }; |
| 331 | |
| 332 | const PosixThreadImpl = struct { |
| 333 | const c = std.c; |
| 334 | |
| 335 | pub const ThreadHandle = c.pthread_t; |
| 336 | |
| 337 | fn getCurrentId() Id { |
| 338 | switch (target.os.tag) { |
| 339 | .linux => { |
| 340 | return LinuxThreadImpl.getCurrentId(); |
| 341 | }, |
| 342 | .macos, .ios, .watchos, .tvos => { |
| 343 | var thread_id: u64 = undefined; |
| 344 | // Pass thread=null to get the current thread ID. |
| 345 | assert(c.pthread_threadid_np(null, &thread_id) == 0); |
| 346 | return thread_id; |
| 347 | }, |
| 348 | .dragonfly => { |
| 349 | return @bitCast(u32, c.lwp_gettid()); |
| 350 | }, |
| 351 | .netbsd => { |
| 352 | return @bitCast(u32, c._lwp_self()); |
| 353 | }, |
| 354 | .freebsd => { |
| 355 | return @bitCast(u32, c.pthread_getthreadid_np()); |
| 356 | }, |
| 357 | .openbsd => { |
| 358 | return @bitCast(u32, c.getthrid()); |
| 359 | }, |
| 360 | .haiku => { |
| 361 | return @bitCast(u32, c.find_thread(null)); |
| 362 | }, |
| 363 | else => { |
| 364 | return @ptrToInt(c.pthread_self()); |
| 365 | }, |
| 324 | 366 | } |
| 325 | | }; |
| 367 | } |
| 368 | |
| 369 | fn getCpuCount() !usize { |
| 370 | switch (target.os.tag) { |
| 371 | .linux => { |
| 372 | return LinuxThreadImpl.getCpuCount(); |
| 373 | }, |
| 374 | .openbsd => { |
| 375 | var count: c_int = undefined; |
| 376 | var count_size: usize = @sizeOf(c_int); |
| 377 | const mib = [_]c_int{ os.CTL_HW, os.HW_NCPUONLINE }; |
| 378 | os.sysctl(&mib, &count, &count_size, null, 0) catch |err| switch (err) { |
| 379 | error.NameTooLong, error.UnknownName => unreachable, |
| 380 | else => |e| return e, |
| 381 | }; |
| 382 | return @intCast(usize, count); |
| 383 | }, |
| 384 | .haiku => { |
| 385 | var count: u32 = undefined; |
| 386 | var system_info: os.system_info = undefined; |
| 387 | _ = os.system.get_system_info(&system_info); // always returns B_OK |
| 388 | count = system_info.cpu_count; |
| 389 | return @intCast(usize, count); |
| 390 | }, |
| 391 | else => { |
| 392 | var count: c_int = undefined; |
| 393 | var count_len: usize = @sizeOf(c_int); |
| 394 | const name = if (comptime target.isDarwin()) "hw.logicalcpu" else "hw.ncpu"; |
| 395 | os.sysctlbynameZ(name, &count, &count_len, null, 0) catch |err| switch (err) { |
| 396 | error.NameTooLong, error.UnknownName => unreachable, |
| 397 | else => |e| return e, |
| 398 | }; |
| 399 | return @intCast(usize, count); |
| 400 | }, |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | handle: ThreadHandle, |
| 405 | |
| 406 | fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl { |
| 407 | const Args = @TypeOf(args); |
| 408 | const allocator = std.heap.c_allocator; |
| 409 | |
| 410 | const Instance = struct { |
| 411 | fn entryFn(raw_arg: ?*c_void) callconv(.C) ?*c_void { |
| 412 | // @alignCast() below doesn't support zero-sized-types (ZST) |
| 413 | if (@sizeOf(Args) < 1) { |
| 414 | return callFn(f, @as(Args, undefined)); |
| 415 | } |
| 416 | |
| 417 | const args_ptr = @ptrCast(*Args, @alignCast(@alignOf(Args), raw_arg)); |
| 418 | defer allocator.destroy(args_ptr); |
| 419 | return callFn(f, args_ptr.*); |
| 420 | } |
| 421 | }; |
| 422 | |
| 423 | const args_ptr = try allocator.create(Args); |
| 424 | args_ptr.* = args; |
| 425 | errdefer allocator.destroy(args_ptr); |
| 326 | 426 | |
| 327 | | if (Thread.use_pthreads) { |
| 328 | 427 | var attr: c.pthread_attr_t = undefined; |
| 329 | 428 | if (c.pthread_attr_init(&attr) != 0) return error.SystemResources; |
| 330 | 429 | defer assert(c.pthread_attr_destroy(&attr) == 0); |
| 331 | 430 | |
| 332 | | const thread_obj = try std.heap.c_allocator.create(Thread); |
| 333 | | errdefer std.heap.c_allocator.destroy(thread_obj); |
| 334 | | if (@sizeOf(Context) > 0) { |
| 335 | | thread_obj.data.memory = try std.heap.c_allocator.allocAdvanced( |
| 336 | | u8, |
| 337 | | @alignOf(Context), |
| 338 | | @sizeOf(Context), |
| 339 | | .at_least, |
| 340 | | ); |
| 341 | | errdefer std.heap.c_allocator.free(thread_obj.data.memory); |
| 342 | | mem.copy(u8, thread_obj.data.memory, mem.asBytes(&context)); |
| 343 | | } else { |
| 344 | | thread_obj.data.memory = @as([*]u8, undefined)[0..0]; |
| 345 | | } |
| 346 | | |
| 347 | 431 | // Use the same set of parameters used by the libc-less impl. |
| 348 | | assert(c.pthread_attr_setstacksize(&attr, default_stack_size) == 0); |
| 349 | | assert(c.pthread_attr_setguardsize(&attr, mem.page_size) == 0); |
| 432 | const stack_size = std.math.max(config.stack_size, 16 * 1024); |
| 433 | assert(c.pthread_attr_setstacksize(&attr, stack_size) == 0); |
| 434 | assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == 0); |
| 350 | 435 | |
| 351 | | const err = c.pthread_create( |
| 352 | | &thread_obj.data.handle, |
| 436 | var handle: c.pthread_t = undefined; |
| 437 | switch (c.pthread_create( |
| 438 | &handle, |
| 353 | 439 | &attr, |
| 354 | | MainFuncs.posixThreadMain, |
| 355 | | thread_obj.data.memory.ptr, |
| 356 | | ); |
| 357 | | switch (err) { |
| 358 | | 0 => return thread_obj, |
| 440 | Instance.entryFn, |
| 441 | if (@sizeOf(Args) > 1) @ptrCast(*c_void, args_ptr) else undefined, |
| 442 | )) { |
| 443 | 0 => return Impl{ .handle = handle }, |
| 359 | 444 | os.EAGAIN => return error.SystemResources, |
| 360 | 445 | os.EPERM => unreachable, |
| 361 | 446 | os.EINVAL => unreachable, |
| 362 | | else => return os.unexpectedErrno(err), |
| 447 | else => |err| return os.unexpectedErrno(err), |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | fn getHandle(self: Impl) ThreadHandle { |
| 452 | return self.handle; |
| 453 | } |
| 454 | |
| 455 | fn detach(self: Impl) void { |
| 456 | switch (c.pthread_detach(self.handle)) { |
| 457 | 0 => {}, |
| 458 | os.EINVAL => unreachable, // thread handle is not joinable |
| 459 | os.ESRCH => unreachable, // thread handle is invalid |
| 460 | else => unreachable, |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | fn join(self: Impl) void { |
| 465 | switch (c.pthread_join(self.handle, null)) { |
| 466 | 0 => {}, |
| 467 | os.EINVAL => unreachable, // thread handle is not joinable (or another thread is already joining in) |
| 468 | os.ESRCH => unreachable, // thread handle is invalid |
| 469 | os.EDEADLK => unreachable, // two threads tried to join each other |
| 470 | else => unreachable, |
| 363 | 471 | } |
| 472 | } |
| 473 | }; |
| 474 | |
| 475 | const LinuxThreadImpl = struct { |
| 476 | const linux = os.linux; |
| 364 | 477 | |
| 365 | | return thread_obj; |
| 478 | pub const ThreadHandle = i32; |
| 479 | |
| 480 | threadlocal var tls_thread_id: ?Id = null; |
| 481 | |
| 482 | fn getCurrentId() Id { |
| 483 | return tls_thread_id orelse { |
| 484 | const tid = @bitCast(u32, linux.gettid()); |
| 485 | tls_thread_id = tid; |
| 486 | return tid; |
| 487 | }; |
| 366 | 488 | } |
| 367 | 489 | |
| 368 | | var guard_end_offset: usize = undefined; |
| 369 | | var stack_end_offset: usize = undefined; |
| 370 | | var thread_start_offset: usize = undefined; |
| 371 | | var context_start_offset: usize = undefined; |
| 372 | | var tls_start_offset: usize = undefined; |
| 373 | | const mmap_len = blk: { |
| 374 | | var l: usize = mem.page_size; |
| 375 | | // Allocate a guard page right after the end of the stack region |
| 376 | | guard_end_offset = l; |
| 377 | | // The stack itself, which grows downwards. |
| 378 | | l = mem.alignForward(l + default_stack_size, mem.page_size); |
| 379 | | stack_end_offset = l; |
| 380 | | // Above the stack, so that it can be in the same mmap call, put the Thread object. |
| 381 | | l = mem.alignForward(l, @alignOf(Thread)); |
| 382 | | thread_start_offset = l; |
| 383 | | l += @sizeOf(Thread); |
| 384 | | // Next, the Context object. |
| 385 | | if (@sizeOf(Context) != 0) { |
| 386 | | l = mem.alignForward(l, @alignOf(Context)); |
| 387 | | context_start_offset = l; |
| 388 | | l += @sizeOf(Context); |
| 490 | fn getCpuCount() !usize { |
| 491 | const cpu_set = try os.sched_getaffinity(0); |
| 492 | // TODO: should not need this usize cast |
| 493 | return @as(usize, os.CPU_COUNT(cpu_set)); |
| 494 | } |
| 495 | |
| 496 | thread: *ThreadCompletion, |
| 497 | |
| 498 | const ThreadCompletion = struct { |
| 499 | completion: Completion = Completion.init(.running), |
| 500 | child_tid: Atomic(i32) = Atomic(i32).init(1), |
| 501 | parent_tid: i32 = undefined, |
| 502 | mapped: []align(std.mem.page_size) u8, |
| 503 | |
| 504 | /// Calls `munmap(mapped.ptr, mapped.len)` then `exit(1)` without touching the stack (which lives in `mapped.ptr`). |
| 505 | /// Ported over from musl libc's pthread detached implementation: |
| 506 | /// https://github.com/ifduyue/musl/search?q=__unmapself |
| 507 | fn freeAndExit(self: *ThreadCompletion) noreturn { |
| 508 | const unmap_and_exit: []const u8 = switch (target.cpu.arch) { |
| 509 | .i386 => ( |
| 510 | \\ movl $91, %%eax |
| 511 | \\ movl %[ptr], %%ebx |
| 512 | \\ movl %[len], %%ecx |
| 513 | \\ int $128 |
| 514 | \\ movl $1, %%eax |
| 515 | \\ movl $0, %%ebx |
| 516 | \\ int $128 |
| 517 | ), |
| 518 | .x86_64 => ( |
| 519 | \\ movq $11, %%rax |
| 520 | \\ movq %[ptr], %%rbx |
| 521 | \\ movq %[len], %%rcx |
| 522 | \\ syscall |
| 523 | \\ movq $60, %%rax |
| 524 | \\ movq $1, %%rdi |
| 525 | \\ syscall |
| 526 | ), |
| 527 | .arm, .armeb, .thumb, .thumbeb => ( |
| 528 | \\ mov r7, #91 |
| 529 | \\ mov r0, %[ptr] |
| 530 | \\ mov r1, %[len] |
| 531 | \\ svc 0 |
| 532 | \\ mov r7, #1 |
| 533 | \\ mov r0, #0 |
| 534 | \\ svc 0 |
| 535 | ), |
| 536 | .aarch64, .aarch64_be, .aarch64_32 => ( |
| 537 | \\ mov x8, #215 |
| 538 | \\ mov x0, %[ptr] |
| 539 | \\ mov x1, %[len] |
| 540 | \\ svc 0 |
| 541 | \\ mov x8, #93 |
| 542 | \\ mov x0, #0 |
| 543 | \\ svc 0 |
| 544 | ), |
| 545 | .mips, .mipsel => ( |
| 546 | \\ move $sp, $25 |
| 547 | \\ li $2, 4091 |
| 548 | \\ move $4, %[ptr] |
| 549 | \\ move $5, %[len] |
| 550 | \\ syscall |
| 551 | \\ li $2, 4001 |
| 552 | \\ li $4, 0 |
| 553 | \\ syscall |
| 554 | ), |
| 555 | .mips64, .mips64el => ( |
| 556 | \\ li $2, 4091 |
| 557 | \\ move $4, %[ptr] |
| 558 | \\ move $5, %[len] |
| 559 | \\ syscall |
| 560 | \\ li $2, 4001 |
| 561 | \\ li $4, 0 |
| 562 | \\ syscall |
| 563 | ), |
| 564 | .powerpc, .powerpcle, .powerpc64, .powerpc64le => ( |
| 565 | \\ li 0, 91 |
| 566 | \\ mr %[ptr], 3 |
| 567 | \\ mr %[len], 4 |
| 568 | \\ sc |
| 569 | \\ li 0, 1 |
| 570 | \\ li 3, 0 |
| 571 | \\ sc |
| 572 | \\ blr |
| 573 | ), |
| 574 | .riscv64 => ( |
| 575 | \\ li a7, 215 |
| 576 | \\ mv a0, %[ptr] |
| 577 | \\ mv a1, %[len] |
| 578 | \\ ecall |
| 579 | \\ li a7, 93 |
| 580 | \\ mv a0, zero |
| 581 | \\ ecall |
| 582 | ), |
| 583 | else => |cpu_arch| { |
| 584 | @compileLog("Unsupported linux arch ", cpu_arch); |
| 585 | }, |
| 586 | }; |
| 587 | |
| 588 | asm volatile (unmap_and_exit |
| 589 | : |
| 590 | : [ptr] "r" (@ptrToInt(self.mapped.ptr)), |
| 591 | [len] "r" (self.mapped.len) |
| 592 | : "memory" |
| 593 | ); |
| 594 | |
| 595 | unreachable; |
| 389 | 596 | } |
| 390 | | // Finally, the Thread Local Storage, if any. |
| 391 | | l = mem.alignForward(l, os.linux.tls.tls_image.alloc_align); |
| 392 | | tls_start_offset = l; |
| 393 | | l += os.linux.tls.tls_image.alloc_size; |
| 394 | | // Round the size to the page size. |
| 395 | | break :blk mem.alignForward(l, mem.page_size); |
| 396 | 597 | }; |
| 397 | 598 | |
| 398 | | const mmap_slice = mem: { |
| 399 | | // Map the whole stack with no rw permissions to avoid |
| 400 | | // committing the whole region right away |
| 401 | | const mmap_slice = os.mmap( |
| 599 | fn spawn(config: SpawnConfig, comptime f: anytype, args: anytype) !Impl { |
| 600 | const Args = @TypeOf(args); |
| 601 | const Instance = struct { |
| 602 | fn_args: Args, |
| 603 | thread: ThreadCompletion, |
| 604 | |
| 605 | fn entryFn(raw_arg: usize) callconv(.C) u8 { |
| 606 | const self = @intToPtr(*@This(), raw_arg); |
| 607 | defer switch (self.thread.completion.swap(.completed, .SeqCst)) { |
| 608 | .running => {}, |
| 609 | .completed => unreachable, |
| 610 | .detached => self.thread.freeAndExit(), |
| 611 | }; |
| 612 | return callFn(f, self.fn_args); |
| 613 | } |
| 614 | }; |
| 615 | |
| 616 | var guard_offset: usize = undefined; |
| 617 | var stack_offset: usize = undefined; |
| 618 | var tls_offset: usize = undefined; |
| 619 | var instance_offset: usize = undefined; |
| 620 | |
| 621 | const map_bytes = blk: { |
| 622 | var bytes: usize = std.mem.page_size; |
| 623 | guard_offset = bytes; |
| 624 | |
| 625 | bytes += std.math.max(std.mem.page_size, config.stack_size); |
| 626 | bytes = std.mem.alignForward(bytes, std.mem.page_size); |
| 627 | stack_offset = bytes; |
| 628 | |
| 629 | bytes = std.mem.alignForward(bytes, linux.tls.tls_image.alloc_align); |
| 630 | tls_offset = bytes; |
| 631 | bytes += linux.tls.tls_image.alloc_size; |
| 632 | |
| 633 | bytes = std.mem.alignForward(bytes, @alignOf(Instance)); |
| 634 | instance_offset = bytes; |
| 635 | bytes += @sizeOf(Instance); |
| 636 | |
| 637 | bytes = std.mem.alignForward(bytes, std.mem.page_size); |
| 638 | break :blk bytes; |
| 639 | }; |
| 640 | |
| 641 | // map all memory needed without read/write permissions |
| 642 | // to avoid committing the whole region right away |
| 643 | const mapped = os.mmap( |
| 402 | 644 | null, |
| 403 | | mmap_len, |
| 645 | map_bytes, |
| 404 | 646 | os.PROT_NONE, |
| 405 | 647 | os.MAP_PRIVATE | os.MAP_ANONYMOUS, |
| 406 | 648 | -1, |
| ... | ... | @@ -411,73 +653,57 @@ pub fn spawn(comptime startFn: anytype, context: SpawnContextType(@TypeOf(startF |
| 411 | 653 | error.PermissionDenied => unreachable, |
| 412 | 654 | else => |e| return e, |
| 413 | 655 | }; |
| 414 | | errdefer os.munmap(mmap_slice); |
| 656 | assert(mapped.len >= map_bytes); |
| 657 | errdefer os.munmap(mapped); |
| 415 | 658 | |
| 416 | | // Map everything but the guard page as rw |
| 659 | // map everything but the guard page as read/write |
| 417 | 660 | os.mprotect( |
| 418 | | mmap_slice[guard_end_offset..], |
| 661 | mapped[guard_offset..], |
| 419 | 662 | os.PROT_READ | os.PROT_WRITE, |
| 420 | 663 | ) catch |err| switch (err) { |
| 421 | 664 | error.AccessDenied => unreachable, |
| 422 | 665 | else => |e| return e, |
| 423 | 666 | }; |
| 424 | 667 | |
| 425 | | break :mem mmap_slice; |
| 426 | | }; |
| 427 | | |
| 428 | | const mmap_addr = @ptrToInt(mmap_slice.ptr); |
| 429 | | |
| 430 | | const thread_ptr = @alignCast(@alignOf(Thread), @intToPtr(*Thread, mmap_addr + thread_start_offset)); |
| 431 | | thread_ptr.data.memory = mmap_slice; |
| 668 | // Prepare the TLS segment and prepare a user_desc struct when needed on i386 |
| 669 | var tls_ptr = os.linux.tls.prepareTLS(mapped[tls_offset..]); |
| 670 | var user_desc: if (target.cpu.arch == .i386) os.linux.user_desc else void = undefined; |
| 671 | if (target.cpu.arch == .i386) { |
| 672 | defer tls_ptr = @ptrToInt(&user_desc); |
| 673 | user_desc = .{ |
| 674 | .entry_number = os.linux.tls.tls_image.gdt_entry_number, |
| 675 | .base_addr = tls_ptr, |
| 676 | .limit = 0xfffff, |
| 677 | .seg_32bit = 1, |
| 678 | .contents = 0, // Data |
| 679 | .read_exec_only = 0, |
| 680 | .limit_in_pages = 1, |
| 681 | .seg_not_present = 0, |
| 682 | .useable = 1, |
| 683 | }; |
| 684 | } |
| 432 | 685 | |
| 433 | | var arg: usize = undefined; |
| 434 | | if (@sizeOf(Context) != 0) { |
| 435 | | arg = mmap_addr + context_start_offset; |
| 436 | | const context_ptr = @alignCast(@alignOf(Context), @intToPtr(*Context, arg)); |
| 437 | | context_ptr.* = context; |
| 438 | | } |
| 686 | const instance = @ptrCast(*Instance, @alignCast(@alignOf(Instance), &mapped[instance_offset])); |
| 687 | instance.* = .{ |
| 688 | .fn_args = args, |
| 689 | .thread = .{ .mapped = mapped }, |
| 690 | }; |
| 439 | 691 | |
| 440 | | if (std.Target.current.os.tag == .linux) { |
| 441 | | const flags: u32 = os.CLONE_VM | os.CLONE_FS | os.CLONE_FILES | |
| 442 | | os.CLONE_SIGHAND | os.CLONE_THREAD | os.CLONE_SYSVSEM | |
| 692 | const flags: u32 = os.CLONE_THREAD | os.CLONE_DETACHED | |
| 693 | os.CLONE_VM | os.CLONE_FS | os.CLONE_FILES | |
| 443 | 694 | os.CLONE_PARENT_SETTID | os.CLONE_CHILD_CLEARTID | |
| 444 | | os.CLONE_DETACHED | os.CLONE_SETTLS; |
| 445 | | // This structure is only needed when targeting i386 |
| 446 | | var user_desc: if (std.Target.current.cpu.arch == .i386) os.linux.user_desc else void = undefined; |
| 447 | | |
| 448 | | const tls_area = mmap_slice[tls_start_offset..]; |
| 449 | | const tp_value = os.linux.tls.prepareTLS(tls_area); |
| 450 | | |
| 451 | | const newtls = blk: { |
| 452 | | if (std.Target.current.cpu.arch == .i386) { |
| 453 | | user_desc = os.linux.user_desc{ |
| 454 | | .entry_number = os.linux.tls.tls_image.gdt_entry_number, |
| 455 | | .base_addr = tp_value, |
| 456 | | .limit = 0xfffff, |
| 457 | | .seg_32bit = 1, |
| 458 | | .contents = 0, // Data |
| 459 | | .read_exec_only = 0, |
| 460 | | .limit_in_pages = 1, |
| 461 | | .seg_not_present = 0, |
| 462 | | .useable = 1, |
| 463 | | }; |
| 464 | | break :blk @ptrToInt(&user_desc); |
| 465 | | } else { |
| 466 | | break :blk tp_value; |
| 467 | | } |
| 468 | | }; |
| 695 | os.CLONE_SIGHAND | os.CLONE_SYSVSEM | os.CLONE_SETTLS; |
| 469 | 696 | |
| 470 | | const rc = os.linux.clone( |
| 471 | | MainFuncs.linuxThreadMain, |
| 472 | | mmap_addr + stack_end_offset, |
| 697 | switch (linux.getErrno(linux.clone( |
| 698 | Instance.entryFn, |
| 699 | @ptrToInt(&mapped[stack_offset]), |
| 473 | 700 | flags, |
| 474 | | arg, |
| 475 | | &thread_ptr.data.handle, |
| 476 | | newtls, |
| 477 | | &thread_ptr.data.handle, |
| 478 | | ); |
| 479 | | switch (os.errno(rc)) { |
| 480 | | 0 => return thread_ptr, |
| 701 | @ptrToInt(instance), |
| 702 | &instance.thread.parent_tid, |
| 703 | tls_ptr, |
| 704 | &instance.thread.child_tid.value, |
| 705 | ))) { |
| 706 | 0 => return Impl{ .thread = &instance.thread }, |
| 481 | 707 | os.EAGAIN => return error.ThreadQuotaExceeded, |
| 482 | 708 | os.EINVAL => unreachable, |
| 483 | 709 | os.ENOMEM => return error.SystemResources, |
| ... | ... | @@ -486,100 +712,92 @@ pub fn spawn(comptime startFn: anytype, context: SpawnContextType(@TypeOf(startF |
| 486 | 712 | os.EUSERS => unreachable, |
| 487 | 713 | else => |err| return os.unexpectedErrno(err), |
| 488 | 714 | } |
| 489 | | } else { |
| 490 | | @compileError("Unsupported OS"); |
| 491 | 715 | } |
| 492 | | } |
| 493 | 716 | |
| 494 | | pub const CpuCountError = error{ |
| 495 | | PermissionDenied, |
| 496 | | SystemResources, |
| 497 | | Unexpected, |
| 498 | | }; |
| 717 | fn getHandle(self: Impl) ThreadHandle { |
| 718 | return self.thread.parent_tid; |
| 719 | } |
| 499 | 720 | |
| 500 | | pub fn cpuCount() CpuCountError!usize { |
| 501 | | switch (std.Target.current.os.tag) { |
| 502 | | .linux => { |
| 503 | | const cpu_set = try os.sched_getaffinity(0); |
| 504 | | return @as(usize, os.CPU_COUNT(cpu_set)); // TODO should not need this usize cast |
| 505 | | }, |
| 506 | | .windows => { |
| 507 | | return os.windows.peb().NumberOfProcessors; |
| 508 | | }, |
| 509 | | .openbsd => { |
| 510 | | var count: c_int = undefined; |
| 511 | | var count_size: usize = @sizeOf(c_int); |
| 512 | | const mib = [_]c_int{ os.CTL_HW, os.HW_NCPUONLINE }; |
| 513 | | os.sysctl(&mib, &count, &count_size, null, 0) catch |err| switch (err) { |
| 514 | | error.NameTooLong, error.UnknownName => unreachable, |
| 515 | | else => |e| return e, |
| 516 | | }; |
| 517 | | return @intCast(usize, count); |
| 518 | | }, |
| 519 | | .haiku => { |
| 520 | | var count: u32 = undefined; |
| 521 | | // var system_info: os.system_info = undefined; |
| 522 | | // const rc = os.system.get_system_info(&system_info); |
| 523 | | count = system_info.cpu_count; |
| 524 | | return @intCast(usize, count); |
| 525 | | }, |
| 526 | | else => { |
| 527 | | var count: c_int = undefined; |
| 528 | | var count_len: usize = @sizeOf(c_int); |
| 529 | | const name = if (comptime std.Target.current.isDarwin()) "hw.logicalcpu" else "hw.ncpu"; |
| 530 | | os.sysctlbynameZ(name, &count, &count_len, null, 0) catch |err| switch (err) { |
| 531 | | error.NameTooLong, error.UnknownName => unreachable, |
| 532 | | else => |e| return e, |
| 533 | | }; |
| 534 | | return @intCast(usize, count); |
| 535 | | }, |
| 721 | fn detach(self: Impl) void { |
| 722 | switch (self.thread.completion.swap(.detached, .SeqCst)) { |
| 723 | .running => {}, |
| 724 | .completed => self.join(), |
| 725 | .detached => unreachable, |
| 726 | } |
| 536 | 727 | } |
| 537 | | } |
| 538 | 728 | |
| 539 | | pub fn getCurrentThreadId() u64 { |
| 540 | | switch (std.Target.current.os.tag) { |
| 541 | | .linux => { |
| 542 | | // Use the syscall directly as musl doesn't provide a wrapper. |
| 543 | | return @bitCast(u32, os.linux.gettid()); |
| 544 | | }, |
| 545 | | .windows => { |
| 546 | | return os.windows.kernel32.GetCurrentThreadId(); |
| 547 | | }, |
| 548 | | .macos, .ios, .watchos, .tvos => { |
| 549 | | var thread_id: u64 = undefined; |
| 550 | | // Pass thread=null to get the current thread ID. |
| 551 | | assert(c.pthread_threadid_np(null, &thread_id) == 0); |
| 552 | | return thread_id; |
| 553 | | }, |
| 554 | | .dragonfly => { |
| 555 | | return @bitCast(u32, c.lwp_gettid()); |
| 556 | | }, |
| 557 | | .netbsd => { |
| 558 | | return @bitCast(u32, c._lwp_self()); |
| 559 | | }, |
| 560 | | .freebsd => { |
| 561 | | return @bitCast(u32, c.pthread_getthreadid_np()); |
| 562 | | }, |
| 563 | | .openbsd => { |
| 564 | | return @bitCast(u32, c.getthrid()); |
| 565 | | }, |
| 566 | | .haiku => { |
| 567 | | return @bitCast(u32, c.find_thread(null)); |
| 568 | | }, |
| 569 | | else => { |
| 570 | | @compileError("getCurrentThreadId not implemented for this platform"); |
| 571 | | }, |
| 729 | fn join(self: Impl) void { |
| 730 | defer os.munmap(self.thread.mapped); |
| 731 | |
| 732 | var spin: u8 = 10; |
| 733 | while (true) { |
| 734 | const tid = self.thread.child_tid.load(.SeqCst); |
| 735 | if (tid == 0) { |
| 736 | break; |
| 737 | } |
| 738 | |
| 739 | if (spin > 0) { |
| 740 | spin -= 1; |
| 741 | std.atomic.spinLoopHint(); |
| 742 | continue; |
| 743 | } |
| 744 | |
| 745 | switch (linux.getErrno(linux.futex_wait( |
| 746 | &self.thread.child_tid.value, |
| 747 | linux.FUTEX_WAIT, |
| 748 | tid, |
| 749 | null, |
| 750 | ))) { |
| 751 | 0 => continue, |
| 752 | os.EINTR => continue, |
| 753 | os.EAGAIN => continue, |
| 754 | else => unreachable, |
| 755 | } |
| 756 | } |
| 572 | 757 | } |
| 573 | | } |
| 758 | }; |
| 574 | 759 | |
| 575 | 760 | test "std.Thread" { |
| 576 | | if (!builtin.single_threaded) { |
| 577 | | _ = AutoResetEvent; |
| 578 | | _ = Futex; |
| 579 | | _ = ResetEvent; |
| 580 | | _ = StaticResetEvent; |
| 581 | | _ = Mutex; |
| 582 | | _ = Semaphore; |
| 583 | | _ = Condition; |
| 584 | | } |
| 761 | // Doesn't use testing.refAllDecls() since that would pull in the compileError spinLoopHint. |
| 762 | _ = AutoResetEvent; |
| 763 | _ = Futex; |
| 764 | _ = ResetEvent; |
| 765 | _ = StaticResetEvent; |
| 766 | _ = Mutex; |
| 767 | _ = Semaphore; |
| 768 | _ = Condition; |
| 769 | } |
| 770 | |
| 771 | fn testIncrementNotify(value: *usize, event: *ResetEvent) void { |
| 772 | value.* += 1; |
| 773 | event.set(); |
| 774 | } |
| 775 | |
| 776 | test "Thread.join" { |
| 777 | if (std.builtin.single_threaded) return error.SkipZigTest; |
| 778 | |
| 779 | var value: usize = 0; |
| 780 | var event: ResetEvent = undefined; |
| 781 | try event.init(); |
| 782 | defer event.deinit(); |
| 783 | |
| 784 | const thread = try Thread.spawn(.{}, testIncrementNotify, .{ &value, &event }); |
| 785 | thread.join(); |
| 786 | |
| 787 | try std.testing.expectEqual(value, 1); |
| 788 | } |
| 789 | |
| 790 | test "Thread.detach" { |
| 791 | if (std.builtin.single_threaded) return error.SkipZigTest; |
| 792 | |
| 793 | var value: usize = 0; |
| 794 | var event: ResetEvent = undefined; |
| 795 | try event.init(); |
| 796 | defer event.deinit(); |
| 797 | |
| 798 | const thread = try Thread.spawn(.{}, testIncrementNotify, .{ &value, &event }); |
| 799 | thread.detach(); |
| 800 | |
| 801 | event.wait(); |
| 802 | try std.testing.expectEqual(value, 1); |
| 585 | 803 | } |