signal and thread spawns

This commit is contained in:
Muaz Ahmad 2023-11-27 13:31:53 +05:00
parent c63d0520c7
commit 18a998e737

View file

@ -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});
}
}