From 18a998e7372e95a73dfe3a0416ac666d8b6aac39 Mon Sep 17 00:00:00 2001 From: Muaz Ahmad Date: Mon, 27 Nov 2023 13:31:53 +0500 Subject: [PATCH] signal and thread spawns --- src/threads.zig | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/src/threads.zig b/src/threads.zig index 4a976e1..676e5ed 100644 --- a/src/threads.zig +++ b/src/threads.zig @@ -2,8 +2,21 @@ const std = @import("std"); const util = @import("util.zig"); +const AtomicBool = std.atomic.Atomic(bool); + +const Signals = struct { + quit: AtomicBool, + + const Self = @This(); + + fn init() Self { + return Self { + .quit = AtomicBool.init(false), + }; + } +}; + const QueueWrap = struct { - alloc: std.mem.Allocator, queue: *util.JobQueue, job_pool: util.JobPool, @@ -13,7 +26,6 @@ const QueueWrap = struct { var q = try alloc.create(util.JobQueue); q.* = util.JobQueue.init(job_pool); return Self { - .alloc = alloc, .queue = q, .job_pool = job_pool, }; @@ -23,22 +35,29 @@ const QueueWrap = struct { pub const ThreadManager = struct { threads: std.ArrayList(std.Thread), arena: std.heap.ArenaAllocator, - queue: QueueWrap, + queue_wrp: QueueWrap, job_pool: util.JobPool, + signals: *Signals, const Self = @This(); pub fn init(alloc: std.mem.Allocator, n_quant_jobs: usize) !Self { - _ = n_quant_jobs; var arena = std.heap.ArenaAllocator.init(alloc); var arena_alloc = arena.allocator(); var job_pool = util.JobPool.init(alloc); var thread_mgr = Self { .threads = std.ArrayList(std.Thread).init(arena_alloc), .arena = arena, - .queue = try QueueWrap.init(arena_alloc, job_pool), + .queue_wrp = try QueueWrap.init(arena_alloc, job_pool), .job_pool = job_pool, + .signals = try arena_alloc.create(Signals), }; + thread_mgr.signals.* = Signals.init(); + + for (0..n_quant_jobs) |_| { + try thread_mgr.threads.append(try std.Thread.spawn(.{}, quantize_loop, .{thread_mgr.queue_wrp.queue, thread_mgr.signals})); + } + return thread_mgr; } @@ -47,3 +66,10 @@ pub const ThreadManager = struct { self.job_pool.deinit(); } }; + +fn quantize_loop(queue: *util.JobQueue, signals: *Signals) void { + while (queue.HasJobs() or !signals.quit.load(std.builtin.AtomicOrder.Acquire)) : (std.time.sleep(1)) { + const job = queue.pop() orelse continue; + std.debug.print("{any}\n", .{job}); + } +}