Skip to content

Instantly share code, notes, and snippets.

@itsmontoya
Last active October 3, 2019 03:02
Show Gist options
  • Save itsmontoya/53db1c12ff801da27d676db735ae4d92 to your computer and use it in GitHub Desktop.
Save itsmontoya/53db1c12ff801da27d676db735ae4d92 to your computer and use it in GitHub Desktop.
/*
$ zig run main.zig
/Users/panda/Development/zig/hello_world/main.zig:12:52: error: incompatible types: 'type' and 'SlowAdder'
var co = NewCoroutine(fn (sa1: SlowAdder) bool | sa1 | {
^
/Users/panda/Development/zig/hello_world/main.zig:12:27: note: type 'type' here
var co = NewCoroutine(fn (sa1: SlowAdder) bool | sa1 | {
^
/Users/panda/Development/zig/hello_world/main.zig:12:54: note: type 'SlowAdder' here
var co = NewCoroutine(fn (sa1: SlowAdder) bool | sa1 | {
^
/Users/panda/Development/zig/hello_world/main.zig:26:27: error: incompatible types: 'type' and 'Coroutine'
var loop = fn () void | c | {
^
/Users/panda/Development/zig/hello_world/main.zig:26:16: note: type 'type' here
var loop = fn () void | c | {
^
/Users/panda/Development/zig/hello_world/main.zig:26:29: note: type 'Coroutine' here
var loop = fn () void | c | {
^
*/
const std = @import("std");
const builtin = @import("builtin");
pub fn main() anyerror!void {
var sa1 = SlowAdder{
.a = 1,
.b = 2,
.res = 0,
.delay_duration = 1,
};
var co = NewCoroutine(fn () bool | sa1 | {
return true;
});
await co;
std.debug.warn("{} + {} = {}", co.a, co.b, co.res);
}
fn NewCoroutine(work: fn () bool) Coroutine {
var c = Coroutine{
.done = false,
.work = work,
};
var loop = fn () void | c | {
while (c.do_work()) {}
return;
};
const thread = try std.Thread.spawn({}, loop);
return c;
}
const Coroutine = struct {
done: bool,
frame: anyframe = undefined,
work: fn () bool,
fn do_work(self: Promise) bool {
.done = .work();
if (.done and .frame != undefined) {
resume .frame;
}
return .done;
}
pub fn then(self: Promise) void {
if (.done) {
return;
}
suspend {
comptime assert(@typeOf(@frame()) == *@Frame(.then));
.frame = @frame();
}
}
};
const SlowAdder = struct {
a: i32,
b: i32,
res: i32,
delay_duration: usize,
pub fn add(self: SlowAdder) bool {
std.time.sleep(.delay_duration * std.time.ns_per_s);
self.res = self.a + self.b;
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment