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
///! minimal reproduction: does Io.Evented fiber context-switch work?
///! tests several variants to isolate the failure mode
const std = @import("std");
const Io = std.Io;
var evented: Io.Evented = undefined;
var debug_threaded_io: Io.Threaded = undefined;
pub const std_options_debug_threaded_io: ?*Io.Threaded = &debug_threaded_io;
fn fiberNoSleep(_: Io) void {
std.debug.print(" fiber-nosleep: entered and returning\n", .{});
}
fn fiberSleep(io: Io) void {
std.debug.print(" fiber-sleep: entered, sleeping 50ms\n", .{});
io.sleep(Io.Duration.fromMilliseconds(50), .awake) catch {
std.debug.print(" fiber-sleep: cancelled\n", .{});
return;
};
std.debug.print(" fiber-sleep: woke up\n", .{});
}
fn fiberYieldOnly(io: Io) void {
std.debug.print(" fiber-yield: entered, yielding\n", .{});
io.sleep(Io.Duration.fromMilliseconds(0), .awake) catch {
std.debug.print(" fiber-yield: cancelled\n", .{});
return;
};
std.debug.print(" fiber-yield: resumed\n", .{});
}
pub fn main() !void {
const allocator = std.heap.c_allocator;
debug_threaded_io = Io.Threaded.init(allocator, .{});
try Io.Evented.init(&evented, allocator, .{});
const io = evented.io();
std.debug.print("evented init: ok\n", .{});
// test 1: fiber that returns immediately (no yield)
std.debug.print("test 1: fiber returns immediately\n", .{});
{
var f = try io.concurrent(fiberNoSleep, .{io});
io.sleep(Io.Duration.fromMilliseconds(10), .awake) catch {};
f.cancel(io);
}
std.debug.print("test 1: PASSED\n\n", .{});
// test 2: fiber that yields once (0ms sleep)
std.debug.print("test 2: fiber yields once\n", .{});
{
var f = try io.concurrent(fiberYieldOnly, .{io});
io.sleep(Io.Duration.fromMilliseconds(50), .awake) catch {};
f.cancel(io);
}
std.debug.print("test 2: PASSED\n\n", .{});
// test 3: fiber that sleeps 50ms
std.debug.print("test 3: fiber sleeps 50ms\n", .{});
{
var f = try io.concurrent(fiberSleep, .{io});
io.sleep(Io.Duration.fromMilliseconds(200), .awake) catch {};
f.cancel(io);
}
std.debug.print("test 3: PASSED\n\n", .{});
std.debug.print("all tests passed\n", .{});
}