A thread-safe object pool which will dynamically grow when empty and revert to the configured size.
var pool = try zul.pool.Growing(Expensive, usize).init(allocator, 10_000, .{.count = 100});
defer pool.deinit();
var exp1 = try pool.acquire();
defer pool.release(exp1);
...
const Expensive = struct {
pub fn init(allocator: Allocator, size: usize) !Expensive {
return .{
};
}
pub fn deinit(self: *Expensive) void {
}
pub fn reset(self: *Expensive) void {
}
};
fn Growing(comptime T: type, comptime C: type) Growing(T, C)
The Growing
pool is a generic function that takes two parameters. T
is the type of object being pool. C
is the type of data to pass into T.init
. In many cases, C
will be void
, in which case T.init
will not receive the value:
var pool = try zul.pool.Growing(Expensive, void).init(allocator, {}, .{.count = 100});
defer pool.deinit();
...
const Expensive = struct {
pub fn init(allocator: Allocator) !Expensive {
return .{
};
}
};
T
must have an init(allocator: Allocator, ctx: C) !T
function. It must also have the following two methods: deinit(self: *T) void
and reset(self: *T) void
. Because the pool will dynamically create T
when empty, deinit
will be called when items are released back into a full pool (as well as when pool.deinit
is called). reset
is called whenever an item is released back into the pool.
init(...) !Growing
fn init(
allocator: std.mem.Allocator,
ctx: C
opts: .{
.count: usize,
}
) !Growing(T, C)