From ff2128ac06a3b480bf5e22b00b3360ae7b361a5d Mon Sep 17 00:00:00 2001 From: Dan Cojocaru Date: Sat, 17 Feb 2024 13:36:10 +0100 Subject: [PATCH] Add mutex to fix crashing --- src/departure.zig | 16 ++++++++++++---- src/state.zig | 1 + 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/departure.zig b/src/departure.zig index d89477f..4629d48 100644 --- a/src/departure.zig +++ b/src/departure.zig @@ -75,6 +75,8 @@ fn fetchThread(state: *AppState) !void { std.debug.print("[departure/fetchThread] JSON parse error: {}\n", .{err}); continue; }; + state.departure_screen_state.mutex.lock(); + defer state.departure_screen_state.mutex.unlock(); if (state.departure_screen_state.fetch_result) |old_result| { old_result.deinit(); } @@ -532,7 +534,9 @@ pub fn render(state: *AppState) !void { rl.KEY_MINUS, rl.KEY_KP_SUBTRACT => { ds.max_next_trains = @max(1, ds.max_next_trains - 1); }, - rl.KEY_EQUAL, rl.KEY_KP_EQUAL => { + rl.KEY_EQUAL, rl.KEY_KP_ADD => { + ds.mutex.lock(); + defer ds.mutex.unlock(); ds.max_next_trains = @min(ds.max_next_trains + 1, if (ds.fetch_result) |fr| @as(c_int, @intCast(fr.value.object.get("departures").?.array.items.len)) else 5); }, rl.KEY_T => { @@ -551,9 +555,13 @@ pub fn render(state: *AppState) !void { rl.BeginDrawing(); defer rl.EndDrawing(); - switch (ds.render_style) { - .db1 => try draw_db1(state), - .ns => try draw_ns(state), + { + ds.mutex.lock(); + defer ds.mutex.unlock(); + switch (ds.render_style) { + .db1 => try draw_db1(state), + .ns => try draw_ns(state), + } } state.close_app = rl.WindowShouldClose(); diff --git a/src/state.zig b/src/state.zig index 5be816d..f454f6e 100644 --- a/src/state.zig +++ b/src/state.zig @@ -25,6 +25,7 @@ pub const RenderStyle = enum(u8) { }; pub const DepartureScreenState = struct { + mutex: std.Thread.Mutex = .{}, station_id: std.ArrayListUnmanaged(u8), platform: std.ArrayListUnmanaged(u8), departure_date: std.time.Instant,