Skip to content

Commit 809c6de

Browse files
committed
poolset: Add optional destructor function
1 parent 7a6447d commit 809c6de

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

Diff for: src/datastore.jl

+8-2
Original file line numberDiff line numberDiff line change
@@ -351,7 +351,8 @@ isondisk(x::DRef) = isondisk(x.id)
351351
function poolset(@nospecialize(x), pid=myid(); size=approx_size(x),
352352
retain=false, restore=false,
353353
device=GLOBAL_DEVICE[], leaf_device=initial_leaf_device(device),
354-
tag=nothing, leaf_tag=Tag())
354+
tag=nothing, leaf_tag=Tag(),
355+
destructor=nothing)
355356
if pid == myid()
356357
id = atomic_add!(id_counter, 1)
357358
sstate = if !restore
@@ -368,7 +369,8 @@ function poolset(@nospecialize(x), pid=myid(); size=approx_size(x),
368369
state = RefState(sstate,
369370
size,
370371
tag,
371-
leaf_tag)
372+
leaf_tag,
373+
destructor)
372374
with_lock(datastore_counters_lock) do
373375
datastore_counters[(pid, id)] = RefCounters()
374376
end
@@ -451,6 +453,10 @@ function datastore_delete(id)
451453
@safe_lock_spin datastore_lock begin
452454
haskey(datastore, id) && delete!(datastore, id)
453455
end
456+
dtor = state.destructor
457+
if dtor !== nothing
458+
errormonitor(Threads.@spawn dtor())
459+
end
454460
return
455461
end
456462

Diff for: src/storage.jl

+3-1
Original file line numberDiff line numberDiff line change
@@ -309,9 +309,11 @@ mutable struct RefState
309309
# Metadata to associate with the reference
310310
tag::Any
311311
leaf_tag::Tag
312+
# Destructor, if any
313+
destructor::Any
312314
end
313315
RefState(storage::StorageState, size::Integer) =
314-
RefState(storage, size, nothing, Tag())
316+
RefState(storage, size, nothing, Tag(), nothing)
315317
function Base.getproperty(state::RefState, field::Symbol)
316318
if field === :storage
317319
throw(ArgumentError("Cannot directly read `:storage` field of `RefState`\nUse `storage_read(state)` instead"))

Diff for: test/runtests.jl

+11-1
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,16 @@ end
246246
end
247247
end
248248

249+
@testset "Destructors" begin
250+
ref_del = Ref(false)
251+
# @eval because testsets retain values in weird ways
252+
x = @eval Ref{Any}(poolset(123; destructor=()->(@assert !$ref_del[]; $ref_del[]=true;)))
253+
@test !ref_del[]
254+
x[] = nothing
255+
GC.gc(); yield()
256+
@test ref_del[]
257+
end
258+
249259
@testset "StorageState" begin
250260
sstate1 = MemPool.StorageState(nothing,
251261
MemPool.StorageLeaf[],
@@ -305,7 +315,7 @@ end
305315
CPURAMDevice(),
306316
Base.Event())
307317
notify(sstate1)
308-
state = MemPool.RefState(sstate1, 64, "abc", MemPool.Tag(SerializationFileDevice=>123))
318+
state = MemPool.RefState(sstate1, 64, "abc", MemPool.Tag(SerializationFileDevice=>123), nothing)
309319
@test state.size == 64
310320
@test MemPool.storage_size(state) == 64
311321
@test_throws ArgumentError state.storage

0 commit comments

Comments
 (0)