Last active
July 18, 2025 03:35
-
-
Save andrewrk/1403c16bd3caa51aa3e8a52ceb3c097b to your computer and use it in GitHub Desktop.
what should be the rules of asyncConcurrent?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const Allocator = std.mem.Allocator; | |
const Io = std.Io; | |
pub const std_options: std.Options = .{ | |
.log_level = .info, | |
}; | |
pub fn main() !void { | |
var debug_allocator: std.heap.DebugAllocator(.{}) = .init; | |
const gpa = debug_allocator.allocator(); | |
//const gpa = std.heap.smp_allocator; | |
var thread_pool: Io.ThreadPool = .init(gpa); | |
defer thread_pool.deinit(); | |
const io = thread_pool.io(); | |
//var event_loop: Io.EventLoop = undefined; | |
//try event_loop.init(gpa); | |
//defer event_loop.deinit(); | |
//const io = event_loop.io(); | |
try example1(io); | |
try example2(io); | |
try example3(io); | |
} | |
///////////////////////////////////// | |
fn example1(io: Io) !void { | |
var long_operation = try io.asyncConcurrent(expensiveComputation, .{}); | |
@atomicStore(bool, &requested_cancel, true, .seq_cst); | |
long_operation.await(io) catch { | |
std.debug.print("example1: canceled\n", .{}); | |
return; | |
}; | |
std.debug.print("example1: finished\n", .{}); | |
} | |
var requested_cancel: bool = false; | |
fn expensiveComputation() error{Canceled}!void { | |
for (0..9999999999999999999) |_| { | |
if (@atomicLoad(bool, &requested_cancel, .seq_cst)) return error.Canceled; | |
} | |
} | |
///////////////////////////////////// | |
fn example2(io: Io) !void { | |
var long_operation = try io.asyncConcurrent(expensiveComputation2, .{io}); | |
long_operation.cancel(io) catch { | |
std.debug.print("example2: canceled\n", .{}); | |
return; | |
}; | |
std.debug.print("example2: finished\n", .{}); | |
} | |
fn expensiveComputation2(io: Io) error{Canceled}!void { | |
for (0..9999999999999999999) |_| { | |
if (io.cancelRequested()) return error.Canceled; | |
} | |
} | |
///////////////////////////////////// | |
fn example3(io: Io) !void { | |
var future = try io.asyncConcurrent(cancelMeDaddy, .{}); | |
defer future.await(io); | |
expensiveComputation3() catch { | |
std.debug.print("example3: canceled\n", .{}); | |
return; | |
}; | |
std.debug.print("example3: finished\n", .{}); | |
} | |
var requested_cancel3: bool = false; | |
fn expensiveComputation3() error{Canceled}!void { | |
for (0..9999999999999999999) |_| { | |
if (@atomicLoad(bool, &requested_cancel3, .seq_cst)) return error.Canceled; | |
} | |
} | |
fn cancelMeDaddy() void { | |
@atomicStore(bool, &requested_cancel3, true, .seq_cst); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment