/
Condition.zig
385 lines (321 loc) · 12 KB
/
Condition.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
const std = @import("../std.zig");
const assert = std.debug.assert;
const testing = std.testing;
const os = std.os;
const builtin = @import("builtin");
const target = builtin.target;
const single_threaded = builtin.single_threaded;
const Atomic = std.atomic.Atomic;
const Futex = std.Thread.Futex;
const Mutex = std.Thread.Mutex;
const Condition = @This();
impl: Impl = .{},
pub fn wait(self: *Condition, held: Mutex.Held, timeout: ?u64) error{TimedOut}!void {
return self.impl.wait(held, timeout);
}
pub fn signal(self: *Condition) void {
return self.impl.wake(false);
}
pub fn broadcast(self: *Condition) void {
return self.impl.wake(true);
}
pub const Impl = if (single_threaded)
SerialImpl
else if (target.os.tag == .windows)
WindowsImpl
else if (target.cpu.arch.ptrBitWidth() >= 64)
Futex64Impl
else
Futex32Impl;
const SerialImpl = struct {
fn wait(self: *Impl, held: Mutex.Held, timeout: ?u64) error{TimedOut}!void {
_ = self;
_ = held;
const timeout_ns = timeout orelse unreachable; // deadlock detected
std.time.sleep(timeout_ns);
return error.TimedOut;
}
fn wake(self: *Impl, notify_all: bool) void {
_ = self;
_ = notify_all;
}
};
const WindowsImpl = struct {
cond: os.windows.CONDITION_VARIABLE = os.windows.CONDITION_VARIABLE_INIT,
fn wait(self: *Impl, held: Mutex.Held, timeout: ?u64) error{TimedOut}!void {
var timeout_ms: os.windows.DWORD = os.windows.INFINITE;
var timeout_overflow = false;
if (timeout) |timeout_ns| {
timeout_ms = std.math.cast(os.windows.DWORD, timeout_ns / std.time.ns_per_ms) catch timeout_ms;
timeout_overflow = timeout_ms == os.windows.INFINITE;
}
const rc = os.windows.kernel32.SleepConditionVariableSRW(
&self.cond,
&held.mutex.impl.srwlock,
timeout_ms,
0, // Mutex acquires the SRWLOCK exclusively
);
if (rc == os.windows.FALSE) {
const err = os.windows.kernel32.GetLastError();
assert(err == .TIMEOUT);
if (!timeout_overflow) {
return error.TimedOut;
}
}
}
fn wake(self: *Impl, notify_all: bool) void {
switch (notify_all) {
true => os.windows.kernel32.WakeAllConditionVariable(&self.cond),
else => os.windows.kernel32.WakeConditionVariable(&self.cond),
}
}
};
/// Simplified implementation of pthread_cond_t ulock variant from darwin libpthread:
/// https://github.com/apple/darwin-libpthread/blob/main/src/pthread_cond.c
const Futex64Impl = struct {
cond: extern union {
qword: Atomic(u64),
state: State,
} = .{ .qword = Atomic(u64).init(0) },
const State = extern struct {
/// Sequence futex that a waiter waits on
seq: Atomic(u32),
/// The number of waiters on the Condition.
/// Incremented and decremented by themselves.
waiters: u16,
/// Claims by `wake()` threads to notify each `waiters`.
signals: u16,
};
fn wait(self: *Impl, held: Mutex.Held, timeout: ?u64) error{TimedOut}!void {
// Add a waiter atomically
const one_waiter = 1 << @bitOffsetOf(State, "waiters");
var cond = self.cond.qword.fetchAdd(one_waiter, .Monotonic);
// Record the sequence to wait on
var state = @bitCast(State, cond);
const wait_seq = state.seq.loadUnchecked();
assert(state.waiters != std.math.maxInt(u16));
// After we wake up, remove our waiter and consume a signal atomically.
defer {
cond = self.cond.qword.load(.Monotonic);
while (true) {
state = @bitCast(State, cond);
state.waiters -= 1;
state.signals = std.math.sub(u16, state.signals, 1) catch 0;
cond = self.cond.qword.tryCompareAndSwap(
cond,
@bitCast(u64, state),
.Acquire,
.Monotonic,
) orelse break;
}
}
held.mutex.impl.release();
defer held.mutex.impl.acquire();
return Futex.wait(
&self.cond.state.seq,
wait_seq,
timeout,
);
}
fn wake(self: *Impl, notify_all: bool) void {
var cond = self.cond.qword.load(.Monotonic);
while (true) {
// Bail if there's no one to wake up
const old_state = @bitCast(State, cond);
if (old_state.waiters == 0) {
return;
}
// Bail if other wake() threads have already committed
// to waking up the waiters on the Condition.
assert(old_state.signals <= old_state.waiters);
if (old_state.signals == old_state.waiters) {
return;
}
// Claim to wake up either all waiters or one waiter.
// A claim also bumps the sequence to actually wake on the Futex.
var new_state = old_state;
new_state.seq.value +%= 1;
new_state.signals = switch (notify_all) {
true => old_state.waiters,
else => old_state.signals + 1,
};
cond = self.cond.qword.tryCompareAndSwap(
cond,
@bitCast(u64, new_state),
.Release,
.Monotonic,
) orelse return Futex.wake(
&self.cond.state.seq,
new_state.signals - old_state.signals, // the number of waiters we claimed to wake up
);
}
}
};
/// 32 bit implementation of Futex64Impl
const Futex32Impl = struct {
seq: Atomic(u32) = Atomic(u32).init(0),
sync: Atomic(u32) = Atomic(u32).init(0),
const State = extern struct {
waiters: u16 = 0,
signals: u16 = 0,
};
fn wait(self: *Impl, held: Mutex.Held, timeout: ?u64) error{TimedOut}!void {
const one_waiter = @bitCast(u32, State{ .waiters = 1 });
var sync = self.sync.fetchAdd(one_waiter, .Monotonic);
var state = @bitCast(State, sync);
assert(state.waiters != std.math.maxInt(u16));
// After waiting, unregister the waiter and consume a signal if there is any.
// Acquire barrier to ensure wake() happens before wait() w.r.t to signaling.
defer {
sync = self.sync.load(.Monotonic);
while (true) {
state = @bitCast(State, sync);
assert(state.waiters > 0);
state.waiters -= 1;
state.signals = std.math.sub(u16, state.signals, 1) catch 0;
sync = self.sync.tryCompareAndSwap(
sync,
@bitCast(u32, state),
.Acquire,
.Monotonic,
) orelse break;
}
}
// Load the sequence and wait on it
// "atomically with respect to access by another thread to the mutex and then the condition variable".
// This means that it's ok if a wake() (sequence increment) is missed while the mutex is still held.
const sequence = self.seq.load(.Monotonic);
held.mutex.impl.release();
defer held.mutex.impl.acquire();
return Futex.wait(
&self.seq,
sequence,
timeout,
);
}
fn wake(self: *Impl, notify_all: bool) void {
var sync = self.sync.load(.Monotonic);
while (true) {
// Bail if there's nothing to wake up
var state = @bitCast(State, sync);
if (state.waiters == 0) {
return;
}
// Bail if there's wake() threads that have already
// reserved the intention to wake up the current waiters.
assert(state.signals <= state.waiters);
if (state.signals == state.waiters) {
return;
}
// Bump the signals count to reserve waking up the waiters.
const old_signals = state.signals;
state.signals = switch (notify_all) {
true => state.waiters,
else => state.signals + 1,
};
// Release meomry ordering to synchronize with the end of wait().
sync = self.sync.tryCompareAndSwap(
sync,
@bitCast(u32, state),
.Release,
.Monotonic,
) orelse {
const notified = state.signals - old_signals;
_ = self.seq.fetchAdd(1, .Monotonic);
return Futex.wake(&self.seq, notified);
};
}
}
};
test "Condition - basic" {
var mutex: Mutex = .{};
var cond: Condition = .{};
// Test that mutex is exclusive
var held = mutex.acquire();
try testing.expectEqual(mutex.tryAcquire(), null);
// Test conditional wait + that the mutex is still locked after
try testing.expectError(error.TimedOut, cond.wait(held, 1));
try testing.expectEqual(mutex.tryAcquire(), null);
// Same thing but for a larger timeout (we can't test null timeout given nothing to wake us up).
try testing.expectError(error.TimedOut, cond.wait(held, 10 * std.time.ns_per_ms));
try testing.expectEqual(mutex.tryAcquire(), null);
// Test again that the mutex can still be acquired after releasing following a wait
held.release();
held = mutex.tryAcquire() orelse return error.MutexTryAcquire;
held.release();
}
test "Condition - wait/signal" {
if (single_threaded) return error.SkipZigTest;
const Context = struct {
lock: Mutex = .{},
cond: Condition = .{},
signaled: bool = false,
fn doWait(self: *@This()) void {
const held = self.lock.acquire();
defer held.release();
while (!self.signaled) {
self.cond.wait(held, null) catch unreachable;
}
}
fn doSignal(self: *@This(), do_broadcast: bool) void {
const held = self.lock.acquire();
defer held.release();
self.signaled = true;
switch (do_broadcast) {
true => self.cond.signal(),
else => self.cond.broadcast(),
}
}
};
for ([_]bool{ false, true }) |do_broadcast| {
var context = Context{};
const wait_signal = try std.Thread.spawn(.{}, Context.doWait, .{&context});
context.doSignal(do_broadcast);
wait_signal.join();
}
}
test "Condition - producer / consumer" {
if (single_threaded) return error.SkipZigTest;
const num_threads = 4;
const Context = struct {
lock: Mutex = .{},
send: Condition = .{},
recv: Condition = .{},
value: usize = 0,
fn doSend(self: *@This(), do_broadcast: bool) void {
const held = self.lock.acquire();
defer held.release();
assert(self.value == 0);
self.value = 1;
switch (do_broadcast) {
true => self.recv.broadcast(),
else => self.recv.signal(),
}
while (self.value != 0) {
self.send.wait(held, null) catch unreachable;
}
}
fn doRecv(self: *@This(), do_broadcast: bool) void {
const held = self.lock.acquire();
defer held.release();
while (self.value == 0) {
self.recv.wait(held, null) catch unreachable;
}
self.value -= 1;
switch (do_broadcast) {
true => self.send.broadcast(),
else => self.send.signal(),
}
}
};
for ([_]bool{ true, false }) |do_broadcast| {
var context = Context{};
var threads: [num_threads]std.Thread = undefined;
for (threads) |*t| t.* = try std.Thread.spawn(.{}, Context.doRecv, .{ &context, do_broadcast });
defer for (threads) |t| t.join();
var i: usize = num_threads;
while (i > 0) : (i -= 1) {
context.doSend(do_broadcast);
}
}
}