Skip to content

Commit

Permalink
fix: use a single mutex in the thread pool
Browse files Browse the repository at this point in the history
On macos, nkt was encountering a `_os_unfair_lock_corruption_abort`
error, as acquiring the synchronization mutex whilst the thread pool was
active somehow triggered UB. The fix is to use the same mutex for
synchronizing the thread map as for the thread pool.
  • Loading branch information
fjebaker committed Sep 29, 2024
1 parent f7f9280 commit 950fde8
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/threads.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ pub const ThreadMap = struct {

pool: std.Thread.Pool,
allocator: std.mem.Allocator,
sync: std.Thread.Mutex = .{},
shared_index: usize = 0,
opts: Options,
wg: std.Thread.WaitGroup = .{},
Expand Down Expand Up @@ -63,8 +62,11 @@ pub const ThreadMap = struct {
id: usize,

fn getNextIndex(w: @This()) usize {
w.parent.sync.lock();
defer w.parent.sync.unlock();
const mut = &w.parent.pool.mutex;

mut.lock();
defer mut.unlock();

const i = w.parent.shared_index;
w.parent.shared_index += w.chunk_size;
return i;
Expand Down Expand Up @@ -95,7 +97,14 @@ pub const ThreadMap = struct {
.chunk_size = opts.chunk_size,
.id = i,
};
self.shared_index += opts.chunk_size;

{
// this could be a race condition so need to lock to increment
self.pool.mutex.lock();
defer self.pool.mutex.unlock();
self.shared_index += opts.chunk_size;
}

try self.pool.spawn(Wrapper.doWork, .{w});
}
}
Expand Down

0 comments on commit 950fde8

Please sign in to comment.