Is there a way to kill/cancel a thread in Zig?

Don’t do this.

Java found out the hard way and actually deprecated Thread.stop().

Learn from the mistakes of your elders. :slight_smile:

3 Likes

For zig 0.14 set

const Atomic = std.atomic.Value;
1 Like

Not currently, but if you check out the async-await-demo branch…

const builtin = @import("builtin");
const std = @import("std");

pub const std_options: std.Options = .{
    .log_level = .info,
};

var debug_allocator: std.heap.DebugAllocator(.{}) = .init;

pub fn main() !void {
    const gpa = switch (builtin.mode) {
        .Debug => debug_allocator.allocator(),
        .ReleaseFast, .ReleaseSafe, .ReleaseSmall => std.heap.smp_allocator,
    };

    var event_loop: std.Io.EventLoop = undefined;
    try event_loop.init(gpa);
    defer event_loop.deinit();
    const io = event_loop.io();

    var print_ints_future = io.async(printIntegers, .{io});
    try io.sleepDuration(.ms(10));
    print_ints_future.cancel(io) catch |err| {
        std.debug.print("printIntegers error: {t}\n", .{err});
    };
}

fn printIntegers(io: std.Io) !void {
    for (0..1_000_000) |i| {
        std.debug.print("{d}\n", .{i});
        try io.sleepDuration(.ms(1));
    }
}

Output:

andy@bark ~/s/z/build-release (async-await-demo)> stage3/bin/zig build-exe test.zig
andy@bark ~/s/z/build-release (async-await-demo)> ./test
0
1
2
3
4
5
6
7
8
9
printIntegers error: Canceled
andy@bark ~/s/z/build-release (async-await-demo)> 
16 Likes