improving device allocator
Build / build (push) Successful in 1m20s
Test / build_and_test (push) Failing after 6m6s

This commit is contained in:
2026-05-08 16:12:34 +02:00
parent e793cb6c3f
commit 1f23d290cb
6 changed files with 76 additions and 27 deletions
+66
View File
@@ -0,0 +1,66 @@
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const Alignment = std.mem.Alignment;
/// Atomic based spin mutex
const AtomicMutex = struct {
mutex: std.atomic.Mutex = .unlocked,
fn lock(self: *@This()) void {
if (self.mutex.tryLock()) {
@branchHint(.likely);
return;
}
while (true) {
if (self.mutex.tryLock()) {
return;
}
}
}
fn unlock(self: *@This()) void {
self.mutex.unlock();
}
};
var mutex: AtomicMutex = .{};
var child_allocator: std.mem.Allocator = if (builtin.link_libc) std.heap.c_allocator else std.heap.smp_allocator;
pub const fallback_host_allocator: Allocator = .{
.ptr = undefined,
.vtable = &vtable,
};
const vtable: Allocator.VTable = .{
.alloc = alloc,
.resize = resize,
.remap = remap,
.free = free,
};
fn alloc(_: *anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 {
mutex.lock();
defer mutex.unlock();
return child_allocator.rawAlloc(len, alignment, ret_addr);
}
fn resize(_: *anyopaque, ptr: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool {
mutex.lock();
defer mutex.unlock();
return child_allocator.rawResize(ptr, alignment, new_len, ret_addr);
}
fn remap(_: *anyopaque, ptr: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
mutex.lock();
defer mutex.unlock();
return child_allocator.rawRemap(ptr, alignment, new_len, ret_addr);
}
fn free(_: *anyopaque, ptr: []u8, alignment: Alignment, ret_addr: usize) void {
mutex.lock();
defer mutex.unlock();
return child_allocator.rawFree(ptr, alignment, ret_addr);
}