|
| 1 | +const std = @import("../index.zig"); |
| 2 | +const builtin = @import("builtin"); |
| 3 | +const Lock = std.event.Lock; |
| 4 | +const Loop = std.event.Loop; |
| 5 | +const AtomicRmwOp = builtin.AtomicRmwOp; |
| 6 | +const AtomicOrder = builtin.AtomicOrder; |
| 7 | +const assert = std.debug.assert; |
| 8 | + |
| 9 | +/// ReturnType should be `void` or `E!void` |
| 10 | +pub fn Group(comptime ReturnType: type) type { |
| 11 | + return struct { |
| 12 | + coro_stack: Stack, |
| 13 | + alloc_stack: Stack, |
| 14 | + lock: Lock, |
| 15 | + |
| 16 | + const Self = this; |
| 17 | + |
| 18 | + const Error = switch (@typeInfo(ReturnType)) { |
| 19 | + builtin.TypeId.ErrorUnion => |payload| payload.error_set, |
| 20 | + else => void, |
| 21 | + }; |
| 22 | + const Stack = std.atomic.Stack(promise->ReturnType); |
| 23 | + |
| 24 | + pub fn init(loop: *Loop) Self { |
| 25 | + return Self{ |
| 26 | + .coro_stack = Stack.init(), |
| 27 | + .alloc_stack = Stack.init(), |
| 28 | + .lock = Lock.init(loop), |
| 29 | + }; |
| 30 | + } |
| 31 | + |
| 32 | + /// Add a promise to the group. Thread-safe. |
| 33 | + pub fn add(self: *Self, handle: promise->ReturnType) (error{OutOfMemory}!void) { |
| 34 | + const node = try self.lock.loop.allocator.create(Stack.Node{ |
| 35 | + .next = undefined, |
| 36 | + .data = handle, |
| 37 | + }); |
| 38 | + self.alloc_stack.push(node); |
| 39 | + } |
| 40 | + |
| 41 | + /// This is equivalent to an async call, but the async function is added to the group, instead |
| 42 | + /// of returning a promise. func must be async and have return type void. |
| 43 | + /// Thread-safe. |
| 44 | + pub fn call(self: *Self, comptime func: var, args: ...) (error{OutOfMemory}!void) { |
| 45 | + const S = struct { |
| 46 | + async fn asyncFunc(node: **Stack.Node, args2: ...) ReturnType { |
| 47 | + // TODO this is a hack to make the memory following be inside the coro frame |
| 48 | + suspend |p| { |
| 49 | + var my_node: Stack.Node = undefined; |
| 50 | + node.* = &my_node; |
| 51 | + resume p; |
| 52 | + } |
| 53 | + |
| 54 | + // TODO this allocation elision should be guaranteed because we await it in |
| 55 | + // this coro frame |
| 56 | + return await (async func(args2) catch unreachable); |
| 57 | + } |
| 58 | + }; |
| 59 | + var node: *Stack.Node = undefined; |
| 60 | + const handle = try async<self.lock.loop.allocator> S.asyncFunc(&node, args); |
| 61 | + node.* = Stack.Node{ |
| 62 | + .next = undefined, |
| 63 | + .data = handle, |
| 64 | + }; |
| 65 | + self.coro_stack.push(node); |
| 66 | + } |
| 67 | + |
| 68 | + /// Wait for all the calls and promises of the group to complete. |
| 69 | + /// Thread-safe. |
| 70 | + pub async fn wait(self: *Self) ReturnType { |
| 71 | + // TODO catch unreachable because the allocation can be grouped with |
| 72 | + // the coro frame allocation |
| 73 | + const held = await (async self.lock.acquire() catch unreachable); |
| 74 | + defer held.release(); |
| 75 | + |
| 76 | + while (self.coro_stack.pop()) |node| { |
| 77 | + if (Error == void) { |
| 78 | + await node.data; |
| 79 | + } else { |
| 80 | + (await node.data) catch |err| { |
| 81 | + self.cancelAll(); |
| 82 | + return err; |
| 83 | + }; |
| 84 | + } |
| 85 | + } |
| 86 | + while (self.alloc_stack.pop()) |node| { |
| 87 | + const handle = node.data; |
| 88 | + self.lock.loop.allocator.destroy(node); |
| 89 | + if (Error == void) { |
| 90 | + await handle; |
| 91 | + } else { |
| 92 | + (await handle) catch |err| { |
| 93 | + self.cancelAll(); |
| 94 | + return err; |
| 95 | + }; |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + |
| 100 | + /// Cancel all the outstanding promises. May only be called if wait was never called. |
| 101 | + pub fn cancelAll(self: *Self) void { |
| 102 | + while (self.coro_stack.pop()) |node| { |
| 103 | + cancel node.data; |
| 104 | + } |
| 105 | + while (self.alloc_stack.pop()) |node| { |
| 106 | + cancel node.data; |
| 107 | + self.lock.loop.allocator.destroy(node); |
| 108 | + } |
| 109 | + } |
| 110 | + }; |
| 111 | +} |
| 112 | + |
| 113 | +test "std.event.Group" { |
| 114 | + var da = std.heap.DirectAllocator.init(); |
| 115 | + defer da.deinit(); |
| 116 | + |
| 117 | + const allocator = &da.allocator; |
| 118 | + |
| 119 | + var loop: Loop = undefined; |
| 120 | + try loop.initMultiThreaded(allocator); |
| 121 | + defer loop.deinit(); |
| 122 | + |
| 123 | + const handle = try async<allocator> testGroup(&loop); |
| 124 | + defer cancel handle; |
| 125 | + |
| 126 | + loop.run(); |
| 127 | +} |
| 128 | + |
| 129 | +async fn testGroup(loop: *Loop) void { |
| 130 | + var count: usize = 0; |
| 131 | + var group = Group(void).init(loop); |
| 132 | + group.add(async sleepALittle(&count) catch @panic("memory")) catch @panic("memory"); |
| 133 | + group.call(increaseByTen, &count) catch @panic("memory"); |
| 134 | + await (async group.wait() catch @panic("memory")); |
| 135 | + assert(count == 11); |
| 136 | + |
| 137 | + var another = Group(error!void).init(loop); |
| 138 | + another.add(async somethingElse() catch @panic("memory")) catch @panic("memory"); |
| 139 | + another.call(doSomethingThatFails) catch @panic("memory"); |
| 140 | + std.debug.assertError(await (async another.wait() catch @panic("memory")), error.ItBroke); |
| 141 | +} |
| 142 | + |
| 143 | +async fn sleepALittle(count: *usize) void { |
| 144 | + std.os.time.sleep(0, 1000000); |
| 145 | + _ = @atomicRmw(usize, count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); |
| 146 | +} |
| 147 | + |
| 148 | +async fn increaseByTen(count: *usize) void { |
| 149 | + var i: usize = 0; |
| 150 | + while (i < 10) : (i += 1) { |
| 151 | + _ = @atomicRmw(usize, count, AtomicRmwOp.Add, 1, AtomicOrder.SeqCst); |
| 152 | + } |
| 153 | +} |
| 154 | + |
| 155 | +async fn doSomethingThatFails() error!void {} |
| 156 | +async fn somethingElse() error!void { |
| 157 | + return error.ItBroke; |
| 158 | +} |
0 commit comments