const Thread = struct next: ?*Threadid: std.Thread.Idhandle: Handlestatus: std.atomic.Value(Status)cancel_protection: Io.CancelProtectionfutex_waiter: if (use_parking_futex) ?*parking_futex.Waiter else ?noreturnAlways released when Status.cancelation is set to .parked.
unpark_flag: UnparkFlagpark_tid: if (ParkTid == std.Thread.Id) void else ParkTidcsprng: CsprngA value that does not alias any other thread id.
fn currentId() std.Thread.Idfn checkCancel() Io.Cancelable!voidThe thread is neither in a syscall nor entering one, but we want to check for cancelation anyway. If there is a pending cancel request, acknowledge it and return error.Canceled.
fn futexWaitUncancelable(ptr: *const u32, expect: u32, timeout_ns: ?u64) voidfn futexWait(ptr: *const u32, expect: u32, timeout_ns: ?u64) Io.Cancelable!voidfn futexWaitInner(ptr: *const u32, expect: u32, uncancelable: bool, timeout_ns: ?u64) Io.Cancelable!voidfn futexWake(ptr: *const u32, max_waiters: u32) voidfn cancelAwaitable(thread: *Thread, awaitable: AwaitableId) boolCancels thread if it is working on awaitable.
It is possible that thread gets canceled by this function, but is blocked in a syscall. In that case, the thread may need to be sent a signal to interrupt the call. This function will return true to indicate this, in which case the caller must call signalCanceledSyscall.
fn signalCanceledSyscall(thread: *Thread, t: *Threaded, awaitable: AwaitableId) boolSends a signal to thread if it is still blocked in a syscall (i.e. has not yet observed the cancelation request from cancelAwaitable).
Unfortunately, the signal could arrive before the syscall actually starts, so the interrupt is missed. To handle this, we may need to send multiple signals. As such, if this function returns true, then it should be called again after a short delay to send another signal if the thread is still blocked. For the implementation, Future.waitForCancelWithSignaling and Group.waitForCancelWithSignaling: they use exponential backoff starting at a 1us delay and doubling each call. In practice, it is rare to send more than one signal.
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342const Thread = struct {
next: ?*Thread,
id: std.Thread.Id,
handle: Handle,
status: std.atomic.Value(Status),
cancel_protection: Io.CancelProtection,
/// Always released when `Status.cancelation` is set to `.parked`.
futex_waiter: if (use_parking_futex) ?*parking_futex.Waiter else ?noreturn,
unpark_flag: UnparkFlag,
park_tid: if (ParkTid == std.Thread.Id) void else ParkTid,
csprng: Csprng,
const Handle = Handle: {
if (std.Thread.use_pthreads) break :Handle std.c.pthread_t;
if (is_windows) break :Handle windows.HANDLE;
break :Handle void;
};
const Status = packed struct(usize) {
/// The specific values of these enum fields are chosen to simplify the implementation of
/// the transformations we need to apply to this state.
cancelation: enum(u3) {
/// The thread has not yet been canceled, and is not in a cancelable operation.
/// To request cancelation, just set the status to `.canceling`.
none = 0b000,
/// The thread is parked in a cancelable futex wait or sleep.
/// Only applicable if `use_parking_futex` or `use_parking_sleep`.
/// To request cancelation, set the status to `.canceling` and unpark the thread.
/// To unpark for another reason (futex wake), set the status to `.none` and unpark the thread.
parked = 0b001,
/// The thread is blocked in a cancelable system call.
/// To request cancelation, set the status to `.blocked_canceling` and repeatedly interrupt the system call until the status changes.
blocked = 0b011,
/// Windows-only: the thread is blocked in an alertable wait via
/// `NtDelayExecution`. To request cancelation, set the status to
/// `blocked_alertable_canceling` and repeatedly alert the thread
/// until the status changes.
blocked_alertable = 0b010,
/// The thread has an outstanding cancelation request but is not in a cancelable operation.
/// When it acknowledges the cancelation, it will set the status to `.canceled`.
canceling = 0b110,
/// The thread has received and acknowledged a cancelation request.
/// If `recancel` is called, the status will revert to `.canceling`, but otherwise, the status
/// will not change for the remainder of this task's execution.
canceled = 0b111,
/// The thread is blocked in a cancelable system call, and is being
/// canceled. The thread which triggered the cancelation will send
/// signals to this thread until its status changes.
blocked_canceling = 0b101,
/// Windows-only: the thread is blocked in an alertable wait via
/// `NtDelayExecution`, and is being canceled. The thread which
/// triggered the cancelation will send signals to this thread
/// until its status changes.
blocked_alertable_canceling = 0b100,
},
/// We cannot turn this value back into a pointer. Instead, it exists so that a task can be
/// canceled by a cmpxchg on thread status: if it is running the task we want to cancel,
/// then update the `cancelation` field.
awaitable: AwaitableId,
};
const SignaleeId = if (std.Thread.use_pthreads) std.c.pthread_t else std.Thread.Id;
threadlocal var current: ?*Thread = null;
/// A value that does not alias any other thread id.
const invalid_id: std.Thread.Id = std.math.maxInt(std.Thread.Id);
fn currentId() std.Thread.Id {
return if (current) |t| t.id else std.Thread.getCurrentId();
}
/// The thread is neither in a syscall nor entering one, but we want to check for cancelation
/// anyway. If there is a pending cancel request, acknowledge it and return `error.Canceled`.
fn checkCancel() Io.Cancelable!void {
const thread = Thread.current orelse return;
switch (thread.cancel_protection) {
.blocked => return,
.unblocked => {},
}
// Here, unlike `Syscall.checkCancel`, it's not particularly likely that we're canceled, so
// it seems preferable to do a cheap atomic load and, in the unlikely case, a separate store
// to acknowledge. Besides, the state transitions we need here can't be done with one atomic
// OR/AND/XOR on `Status.cancelation`, so we don't actually have any other option.
const status = thread.status.load(.monotonic);
switch (status.cancelation) {
.parked => unreachable,
.blocked => unreachable,
.blocked_alertable => unreachable,
.blocked_alertable_canceling => unreachable,
.blocked_canceling => unreachable,
.none, .canceled => {},
.canceling => {
thread.status.store(.{
.cancelation = .canceled,
.awaitable = status.awaitable,
}, .monotonic);
return error.Canceled;
},
}
}
fn futexWaitUncancelable(ptr: *const u32, expect: u32, timeout_ns: ?u64) void {
return Thread.futexWaitInner(ptr, expect, true, timeout_ns) catch unreachable;
}
fn futexWait(ptr: *const u32, expect: u32, timeout_ns: ?u64) Io.Cancelable!void {
return Thread.futexWaitInner(ptr, expect, false, timeout_ns);
}
fn futexWaitInner(ptr: *const u32, expect: u32, uncancelable: bool, timeout_ns: ?u64) Io.Cancelable!void {
@branchHint(.cold);
if (builtin.single_threaded) unreachable; // nobody would ever wake us
if (use_parking_futex) {
return parking_futex.wait(
ptr,
expect,
uncancelable,
if (timeout_ns) |ns| .{ .duration = .{
.raw = .fromNanoseconds(ns),
.clock = .boot,
} } else .none,
);
} else if (builtin.cpu.arch.isWasm()) {
comptime assert(builtin.cpu.has(.wasm, .atomics));
// TODO implement cancelation for WASM futex waits by signaling the futex
if (!uncancelable) try Thread.checkCancel();
const to: i64 = if (timeout_ns) |ns| std.math.cast(i64, ns) orelse std.math.maxInt(i64) else -1;
const signed_expect: i32 = @bitCast(expect);
const result = asm volatile (
\\local.get %[ptr]
\\local.get %[expected]
\\local.get %[timeout]
\\memory.atomic.wait32 0
\\local.set %[ret]
: [ret] "=r" (-> u32),
: [ptr] "r" (ptr),
[expected] "r" (signed_expect),
[timeout] "r" (to),
);
switch (result) {
0 => {}, // ok
1 => {}, // expected != loaded
2 => {}, // timeout
else => assert(!is_debug),
}
} else switch (native_os) {
.linux => {
const linux = std.os.linux;
var ts_buffer: linux.timespec = undefined;
const ts: ?*linux.timespec = if (timeout_ns) |ns| ts: {
ts_buffer = timestampToPosix(ns);
break :ts &ts_buffer;
} else null;
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = linux.futex_4arg(ptr, .{ .cmd = .WAIT, .private = true }, expect, ts);
syscall.finish();
switch (linux.errno(rc)) {
.SUCCESS => {}, // notified by `wake()`
.INTR => {}, // caller's responsibility to retry
.AGAIN => {}, // ptr.* != expect
.INVAL => {}, // possibly timeout overflow
.TIMEDOUT => {},
.FAULT => recoverableOsBugDetected(), // ptr was invalid
else => recoverableOsBugDetected(),
}
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
const c = std.c;
const flags: c.UL = .{
.op = .COMPARE_AND_WAIT,
.NO_ERRNO = true,
};
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const status = switch (darwin_supports_ulock_wait2) {
true => c.__ulock_wait2(flags, ptr, expect, ns: {
const ns = timeout_ns orelse break :ns 0;
if (ns == 0) break :ns 1;
break :ns ns;
}, 0),
false => c.__ulock_wait(flags, ptr, expect, us: {
const ns = timeout_ns orelse break :us 0;
const us = std.math.lossyCast(u32, ns / std.time.ns_per_us);
if (us == 0) break :us 1;
break :us us;
}),
};
syscall.finish();
if (status >= 0) return;
switch (@as(c.E, @fromBackingInt(@intCast(-status)))) {
.INTR => {}, // spurious wake
// Address of the futex was paged out. This is unlikely, but possible in theory, and
// pthread/libdispatch on darwin bother to handle it. In this case we'll return
// without waiting, but the caller should retry anyway.
.FAULT => {},
.TIMEDOUT => {}, // timeout
else => recoverableOsBugDetected(),
}
},
.freebsd => {
const flags = @backingInt(std.c.UMTX_OP.WAIT_UINT_PRIVATE);
var tm_size: usize = 0;
var tm: std.c._umtx_time = undefined;
var tm_ptr: ?*const std.c._umtx_time = null;
if (timeout_ns) |ns| {
tm_ptr = &tm;
tm_size = @sizeOf(@TypeOf(tm));
tm.flags = 0; // use relative time not UMTX_ABSTIME
tm.clockid = .MONOTONIC;
tm.timeout = timestampToPosix(ns);
}
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = std.c._umtx_op(@intFromPtr(ptr), flags, @as(c_ulong, expect), tm_size, @intFromPtr(tm_ptr));
syscall.finish();
if (is_debug) switch (posix.errno(rc)) {
.SUCCESS => {},
.FAULT => unreachable, // one of the args points to invalid memory
.INVAL => unreachable, // arguments should be correct
.TIMEDOUT => {}, // timeout
.INTR => {}, // spurious wake
else => unreachable,
};
},
.openbsd => {
var tm: std.c.timespec = undefined;
var tm_ptr: ?*const std.c.timespec = null;
if (timeout_ns) |ns| {
tm_ptr = &tm;
tm = timestampToPosix(ns);
}
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = std.c.futex(
ptr,
std.c.FUTEX.WAIT | std.c.FUTEX.PRIVATE_FLAG,
@as(c_int, @bitCast(expect)),
tm_ptr,
null, // uaddr2 is ignored
);
syscall.finish();
if (is_debug) switch (posix.errno(rc)) {
.SUCCESS => {},
.NOSYS => unreachable, // constant op known good value
.AGAIN => {}, // contents of uaddr != val
.INVAL => unreachable, // invalid timeout
.TIMEDOUT => {}, // timeout
.INTR => {}, // a signal arrived
.CANCELED => {}, // a signal arrived and SA_RESTART was set
else => unreachable,
};
},
.dragonfly => {
var timeout_us: c_int = undefined;
if (timeout_ns) |ns| {
timeout_us = std.math.cast(c_int, ns / std.time.ns_per_us) orelse std.math.maxInt(c_int);
} else {
timeout_us = 0;
}
const syscall: Syscall = if (uncancelable) .{ .thread = null } else try .start();
const rc = std.c.umtx_sleep(@ptrCast(ptr), @bitCast(expect), timeout_us);
syscall.finish();
if (is_debug) switch (std.posix.errno(rc)) {
.SUCCESS => {},
.BUSY => {}, // ptr != expect
.AGAIN => {}, // maybe timed out, or paged out, or hit 2s kernel refresh
.INTR => {}, // spurious wake
.INVAL => unreachable, // invalid timeout
else => unreachable,
};
},
else => @compileError("unimplemented: futexWait"),
}
}
fn futexWake(ptr: *const u32, max_waiters: u32) void {
@branchHint(.cold);
assert(max_waiters != 0);
if (builtin.single_threaded) return; // nothing to wake up
if (use_parking_futex) {
return parking_futex.wake(ptr, max_waiters);
} else if (builtin.cpu.arch.isWasm()) {
comptime assert(builtin.cpu.has(.wasm, .atomics));
const woken_count = asm volatile (
\\local.get %[ptr]
\\local.get %[waiters]
\\memory.atomic.notify 0
\\local.set %[ret]
: [ret] "=r" (-> u32),
: [ptr] "r" (ptr),
[waiters] "r" (max_waiters),
);
_ = woken_count; // can be 0 when linker flag 'shared-memory' is not enabled
} else switch (native_os) {
.linux => {
const linux = std.os.linux;
switch (linux.errno(linux.futex_3arg(
ptr,
.{ .cmd = .WAKE, .private = true },
@min(max_waiters, std.math.maxInt(i32)),
))) {
.SUCCESS => return, // successful wake up
.INVAL => return, // invalid futex_wait() on ptr done elsewhere
.FAULT => return, // pointer became invalid while doing the wake
else => return recoverableOsBugDetected(), // deadlock due to operating system bug
}
},
.driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
const c = std.c;
const flags: c.UL = .{
.op = .COMPARE_AND_WAIT,
.NO_ERRNO = true,
.WAKE_ALL = max_waiters > 1,
};
while (true) {
const status = c.__ulock_wake(flags, ptr, 0);
if (status >= 0) return;
switch (@as(c.E, @fromBackingInt(@intCast(-status)))) {
.INTR, .CANCELED => continue, // spurious wake()
.FAULT => unreachable, // __ulock_wake doesn't generate EFAULT according to darwin pthread_cond_t
.NOENT => return, // nothing was woken up
.ALREADY => unreachable, // only for UL.Op.WAKE_THREAD
else => unreachable, // deadlock due to operating system bug
}
}
},
.freebsd => {
const rc = std.c._umtx_op(
@intFromPtr(ptr),
@backingInt(std.c.UMTX_OP.WAKE_PRIVATE),
@as(c_ulong, @min(max_waiters, std.math.maxInt(c_int))),
0, // there is no timeout struct
0, // there is no timeout struct pointer
);
switch (posix.errno(rc)) {
.SUCCESS => {},
.FAULT => {}, // it's ok if the ptr doesn't point to valid memory
.INVAL => unreachable, // arguments should be correct
else => unreachable, // deadlock due to operating system bug
}
},
.openbsd => {
const rc = std.c.futex(
ptr,
std.c.FUTEX.WAKE | std.c.FUTEX.PRIVATE_FLAG,
@min(max_waiters, std.math.maxInt(c_int)),
null, // timeout is ignored
null, // uaddr2 is ignored
);
assert(rc >= 0);
},
.dragonfly => {
// will generally return 0 unless the address is bad
_ = std.c.umtx_wakeup(
@ptrCast(ptr),
@min(max_waiters, std.math.maxInt(c_int)),
);
},
else => @compileError("unimplemented: futexWake"),
}
}
/// Cancels `thread` if it is working on `awaitable`.
///
/// It is possible that `thread` gets canceled by this function, but is blocked in a syscall. In
/// that case, the thread may need to be sent a signal to interrupt the call. This function will
/// return `true` to indicate this, in which case the caller must call `signalCanceledSyscall`.
fn cancelAwaitable(thread: *Thread, awaitable: AwaitableId) bool {
var status = thread.status.load(.monotonic);
while (true) {
if (status.awaitable != awaitable) return false; // thread is working on something else
status = switch (status.cancelation) {
.none => thread.status.cmpxchgWeak(
.{ .cancelation = .none, .awaitable = awaitable },
.{ .cancelation = .canceling, .awaitable = awaitable },
.monotonic,
.monotonic,
) orelse return false,
.parked => thread.status.cmpxchgWeak(
.{ .cancelation = .parked, .awaitable = awaitable },
.{ .cancelation = .canceling, .awaitable = awaitable },
.acquire, // acquire `thread.futex_waiter`
.monotonic,
) orelse {
if (!use_parking_futex and !use_parking_sleep) unreachable;
if (thread.futex_waiter) |futex_waiter| {
parking_futex.removeCanceledWaiter(futex_waiter);
}
if (need_unpark_flag) setUnparkFlag(&thread.unpark_flag);
unpark(&.{if (ParkTid == std.Thread.Id) thread.id else thread.park_tid}, null);
return false;
},
.blocked => thread.status.cmpxchgWeak(
.{ .cancelation = .blocked, .awaitable = awaitable },
.{ .cancelation = .blocked_canceling, .awaitable = awaitable },
.monotonic,
.monotonic,
) orelse return true,
.blocked_alertable => thread.status.cmpxchgWeak(
.{ .cancelation = .blocked_alertable, .awaitable = awaitable },
.{ .cancelation = .blocked_alertable_canceling, .awaitable = awaitable },
.monotonic,
.monotonic,
) orelse {
if (!is_windows) unreachable;
return true;
},
.canceling, .canceled => {
// This can happen when the task start raced with the cancelation, so the thread
// saw the cancelation on the future/group *and* we are trying to signal the
// thread here.
return false;
},
.blocked_canceling => unreachable, // `awaitable` has not been canceled before now
.blocked_alertable_canceling => unreachable, // `awaitable` has not been canceled before now
};
}
}
/// Sends a signal to `thread` if it is still blocked in a syscall (i.e. has not yet observed
/// the cancelation request from `cancelAwaitable`).
///
/// Unfortunately, the signal could arrive before the syscall actually starts, so the interrupt
/// is missed. To handle this, we may need to send multiple signals. As such, if this function
/// returns `true`, then it should be called again after a short delay to send another signal if
/// the thread is still blocked. For the implementation, `Future.waitForCancelWithSignaling` and
/// `Group.waitForCancelWithSignaling`: they use exponential backoff starting at a 1us delay and
/// doubling each call. In practice, it is rare to send more than one signal.
fn signalCanceledSyscall(thread: *Thread, t: *Threaded, awaitable: AwaitableId) bool {
const status = thread.status.load(.monotonic);
if (status.awaitable != awaitable) {
// The thread has moved on and is working on something totally different.
return false;
}
// The thread ID and/or handle can be read non-atomically because they never change and were
// released by the store that made `thread` available to us.
switch (status.cancelation) {
.blocked_canceling => if (std.Thread.use_pthreads) {
return switch (std.c.pthread_kill(thread.handle, .IO)) {
0 => true,
else => false,
};
} else switch (native_os) {
.linux => {
const pid: posix.pid_t = pid: {
const cached_pid = @atomicLoad(Pid, &t.pid, .monotonic);
if (cached_pid != .unknown) break :pid @backingInt(cached_pid);
const pid = std.os.linux.getpid();
@atomicStore(Pid, &t.pid, @fromBackingInt(@intCast(pid)), .monotonic);
break :pid pid;
};
return switch (std.os.linux.tgkill(pid, @bitCast(thread.id), .IO)) {
0 => true,
else => false,
};
},
.windows => {
var iosb: windows.IO_STATUS_BLOCK = undefined;
return switch (windows.ntdll.NtCancelSynchronousIoFile(thread.handle, null, &iosb)) {
.NOT_FOUND => true, // this might mean the operation hasn't started yet
.SUCCESS => false, // the OS confirmed that our cancelation worked
else => false,
};
},
else => return false,
},
.blocked_alertable_canceling => {
if (!is_windows) unreachable;
return switch (windows.ntdll.NtAlertThread(thread.handle)) {
.SUCCESS => true,
else => false,
};
},
else => {
// The thread is working on `awaitable`, but no longer needs signaling (they already
// woke up and saw the cancelation).
return false;
},
}
}
/// Like a `*Thread`, but 2 bits smaller than a pointer (because the LSBs are always 0 due to
/// alignment) so that those two bits can be used in a `packed struct`.
const PackedPtr = enum(@Int(.unsigned, @bitSizeOf(usize) - 2)) {
null = 0,
all_ones = std.math.maxInt(@Int(.unsigned, @bitSizeOf(usize) - 2)),
_,
const Split = packed struct(usize) { low: u2, high: PackedPtr };
fn pack(ptr: *Thread) PackedPtr {
const split: Split = @bitCast(@intFromPtr(ptr));
assert(split.low == 0);
return split.high;
}
fn unpack(ptr: PackedPtr) ?*Thread {
const split: Split = .{ .low = 0, .high = ptr };
return @ptrFromInt(@as(usize, @bitCast(split)));
}
};
}