fn acquireThread(s: *SafeAllocator) *Thread s: *SafeAllocator753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772fn acquireThread(s: *SafeAllocator) *Thread {
while (true) {
const t = &s.threads[thread_index];
if (t.mutex.tryLock()) {
@branchHint(.likely);
return t;
}
var max = @atomicLoad(usize, &n_threads, .unordered);
if (max == 0) {
@branchHint(.unlikely);
max = @min(std.Thread.getCpuCount() catch s.threads.len, s.threads.len);
max = @cmpxchgStrong(usize, &n_threads, 0, max, .monotonic, .monotonic) orelse max;
}
thread_index += 1;
// thread_index may be greater than max if the zero is returned by getCpuCount
thread_index *= @intFromBool(thread_index < max);
}
}