-
Book Overview & Buying
-
Table Of Contents
Systems Programming with Zig
By :
Logging information concurrently is a real-world case where multiple threads write to the same log file. What we want is to prevent mixing information from the threads. The solution to that problem is the use of a mutex to ensure thread-safe access to the shared log file. The following example code (ch08/sharedLog.zig) illustrates the technique – feel free to see the implementation of main() at the book GitHub repository:
const std = @import("std");
const Thread = std.Thread;
const LogContext = struct {
io: std.Io,
file: std.Io.File,
mutex: *std.Io.Mutex,
tID: usize,
};
The LogContext structure passes both shared and thread-specific state into our concurrent workers. By bundling a copy of the std.Io.File handle, a pointer to a shared Mutex, and a unique thread identifier, we provide each thread with the exact environment it needs to operate. The logic behind passing the file by value rather than by pointer...