Help Sleep?

I’m trying to create a pod for the terminal in Zig, but I’ve run into the problem: the std.time.sleep library doesn’t exist. Well, at least I thought it would. The Zig documentation shows something similar called std.Io.sleep, but I can’t get it to work. Can anyone tell me or help me?

Hi there! Zig recently introduced a new async I/O, so the standard library of Zig’s master version differs significantly from that of 0.15.2, and sleep is now an I/O concept. For the master version, please refer to the following snippet (Example 1 from the post above by Andrew):

const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;

fn juicyMain(gpa: Allocator, io: Io) !void {
    _ = gpa;

    doWork(io);
}

fn doWork(io: Io) void {
    std.debug.print("working\n", .{});
    io.sleep(.fromSeconds(1), .awake) catch {};
}

pub fn main() !void {
    // Set up allocator.
    var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
    defer assert(debug_allocator.deinit() == .ok);
    const gpa = debug_allocator.allocator();

    // Set up our I/O implementation.
    var threaded: std.Io.Threaded = .init(gpa);
    defer threaded.deinit();
    const io = threaded.io();

    return juicyMain(gpa, io);
}

I also recommend to read that post thoroughly to understand the new async I/O better. :laughing:

6 Likes

For zig 0.15.2 use: std.Thread.sleep.

5 Likes

If you are new to Zig, the X/Y problem here is that you should use Zig 0.15.2 instead of Zig master for your sanity :face_with_tongue:

EDIT: Ahhh, it was std.Thread.sleep. My bad for assuming std.time.sleep does not exist because of master!

EDIT2: always check if you are using the correct version of the documentation: Zig Documentation (the 0.15.2 in the URL)

4 Likes

`sleep()` is just a ‘synchronous’ timer

(meaning that underlying OS syscall will just pause your app, preventing it to do something more useful, I/O, yeah)

if you want ‘asynchronous‘ sleeps, just use OS provided capabilities

  • timerfd_create, Linux
  • IOCP, Windows
  • kqueue(), FreeBSD
1 Like