mirror of
https://codeberg.org/ziglings/exercises.git
synced 2026-06-09 16:39:58 +00:00
Merge pull request 'Demonstrate the benefit of a mutex' (#408) from MatthijsBlom/ziglings:matthijsblom-patch-1 into main
Reviewed-on: https://codeberg.org/ziglings/exercises/pulls/408
This commit is contained in:
@@ -52,6 +52,12 @@ fn increment(io: std.Io, state: *SharedState, times: u32) void {
|
|||||||
state.mutex.??? catch return;
|
state.mutex.??? catch return;
|
||||||
defer state.mutex.unlock(); // <-- what's missing here?
|
defer state.mutex.unlock(); // <-- what's missing here?
|
||||||
|
|
||||||
|
// Sleep to give the other tasks a chance to run in the meantime.
|
||||||
|
// We do this here only to make nondeterminism more visible.
|
||||||
|
io.sleep(std.Io.Duration.fromMilliseconds(1), .awake) catch {};
|
||||||
|
|
||||||
|
// What happens if you neglect to lock the mutex?
|
||||||
|
|
||||||
state.counter += 1;
|
state.counter += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
--- exercises/091_async7.zig 2026-04-02 10:50:08.142508099 +0200
|
--- exercises/091_async7.zig 2026-04-18 23:30:40.963951835 +0200
|
||||||
+++ answers/091_async7.zig 2026-04-02 10:49:59.629341593 +0200
|
+++ answers/091_async7.zig 2026-04-18 23:33:47.313340585 +0200
|
||||||
@@ -49,8 +49,8 @@
|
@@ -49,8 +49,8 @@
|
||||||
for (0..times) |_| {
|
for (0..times) |_| {
|
||||||
// Acquire the lock before modifying shared state.
|
// Acquire the lock before modifying shared state.
|
||||||
@@ -9,5 +9,5 @@
|
|||||||
+ state.mutex.lock(io) catch return;
|
+ state.mutex.lock(io) catch return;
|
||||||
+ defer state.mutex.unlock(io);
|
+ defer state.mutex.unlock(io);
|
||||||
|
|
||||||
state.counter += 1;
|
// Sleep to give the other tasks a chance to run in the meantime.
|
||||||
}
|
// We do this here only to make nondeterminism more visible.
|
||||||
|
|||||||
Reference in New Issue
Block a user