Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix thread safety in atexit(f): Lock access to atexit_hooks #49774

Merged
merged 1 commit into from
May 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion base/initdefs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ end
const atexit_hooks = Callable[
() -> Filesystem.temp_cleanup_purge(force=true)
]
const _atexit_hooks_lock = ReentrantLock()

"""
atexit(f)
Expand All @@ -374,7 +375,7 @@ calls `exit(n)`, then Julia will exit with the exit code corresponding to the
last called exit hook that calls `exit(n)`. (Because exit hooks are called in
LIFO order, "last called" is equivalent to "first registered".)
"""
atexit(f::Function) = (pushfirst!(atexit_hooks, f); nothing)
atexit(f::Function) = Base.@lock _atexit_hooks_lock (pushfirst!(atexit_hooks, f); nothing)

function _atexit(exitcode::Cint)
while !isempty(atexit_hooks)
NHDaly marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
20 changes: 20 additions & 0 deletions test/threads_exec.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1070,4 +1070,24 @@ end
end
end

# issue #49746, thread safety in `atexit(f)`
@testset "atexit thread safety" begin
f = () -> nothing
before_len = length(Base.atexit_hooks)
@sync begin
for _ in 1:1_000_000
Threads.@spawn begin
atexit(f)
end
end
end
@test length(Base.atexit_hooks) == before_len + 1_000_000
@test all(hook -> hook === f, Base.atexit_hooks[1 : 1_000_000])

# cleanup
Base.@lock Base._atexit_hooks_lock begin
deleteat!(Base.atexit_hooks, 1:1_000_000)
end
end

end # main testset