Files
bun.sh/src/threading/guarded_value.zig
taylor.fish a57dee5721 Various safety improvements (safety.ThreadLock, stack traces, MimallocArena, RefCount, safety.alloc) (#21726)
* Move `DebugThreadLock` to `bun.safety`
* Enable in `ci_assert` builds, but store stack traces only in debug
builds
  * Reduce size of struct by making optional field non-optional
* Add `initLockedIfNonComptime` as a workaround for not being able to
call `initLocked` in comptime contexts
* Add `lockOrAssert` method to acquire the lock if unlocked, or else
assert that the current thread acquired the lock
* Add stack traces to `CriticalSection` and `AllocPtr` in debug builds
* Make `MimallocArena.init` infallible
* Make `MimallocArena.heap` non-nullable
* Rename `RefCount.active_counts` to `raw_count` and provide read-only
`get` method
* Add `bun.safety.alloc.assertEq` to assert that two allocators are
equal (avoiding comparison of undefined `ptr`s)

(For internal tracking: fixes STAB-917, STAB-918, STAB-962, STAB-963,
STAB-964, STAB-965)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2025-08-11 13:40:07 -07:00

33 lines
1.1 KiB
Zig

/// A wrapper around a mutex, and a value protected by the mutex.
/// `Mutex` should have `lock` and `unlock` methods and should be initializable with `.{}`.
pub fn GuardedValue(comptime Value: type, comptime Mutex: type) type {
return struct {
const Self = @This();
/// The raw value. Don't use this if there might be concurrent accesses.
unsynchronized_value: Value,
mutex: Mutex,
pub fn init(value: Value, mutex: Mutex) Self {
return .{ .unsynchronized_value = value, .mutex = mutex };
}
/// Lock the mutex and return a pointer to the value. Remember to call `unlock`!
pub fn lock(self: *Self) *Value {
self.mutex.lock();
return &self.unsynchronized_value;
}
/// Unlock the mutex. Don't use any pointers returned by `lock` after calling this method!
pub fn unlock(self: *Self) void {
self.mutex.unlock();
}
};
}
pub fn DebugGuardedValue(comptime Value: type) type {
return GuardedValue(Value, bun.safety.ThreadLock);
}
const bun = @import("bun");