Skip to content

Instantly share code, notes, and snippets.

@andrewrk
Last active March 23, 2020 18:42
Show Gist options
  • Save andrewrk/ef55e65f7dc2a174c3d8fad2adfeb46f to your computer and use it in GitHub Desktop.
Save andrewrk/ef55e65f7dc2a174c3d8fad2adfeb46f to your computer and use it in GitHub Desktop.
using async/await manually with threads
const std = @import("std");
var all_threads: [10]*std.Thread = undefined;
var next_thread_index: usize = 0;
pub fn main() anyerror!void {
_ = async asyncMain();
var i: usize = 0;
while (i < next_thread_index) : (i += 1) {
all_threads[i].wait();
}
}
fn asyncMain() void {
var first_half = async addSomeNumbersTogether(0, 100000000);
var second_half = async addSomeNumbersTogether(100000000, 200000000);
const total = await first_half + await second_half;
std.debug.warn("total: {}\n", .{total});
}
fn addSomeNumbersTogether(start: u64, end: u64) u64 {
doThisInANewThread();
var sum: u64 = 0;
var i: u64 = start;
while (i < end) : (i += 1) {
sum += i;
}
return sum;
}
fn doThisInANewThread() void {
suspend {
const my_frame: anyframe = @frame();
if (std.Thread.spawn(my_frame, resumeMePleaseKThx)) |t| {
// Does not need to be atomic. In this small example, only the "main thread"
// will access these global variables.
all_threads[next_thread_index] = t;
next_thread_index += 1;
} else |_| {
// Unable to spawn thread. Oh well, we'll just do the thing without
// changing threads.
resume @frame();
}
}
}
fn resumeMePleaseKThx(frame: anyframe) void {
resume frame;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment