Skip to content
Merged
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
25 changes: 14 additions & 11 deletions src/crystal/at_exit_handlers.cr
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
# :nodoc:
module Crystal::AtExitHandlers
private class_getter(handlers) { [] of Int32, ::Exception? -> }
@@mutex = ::Thread::Mutex.new

def self.add(handler)
handlers << handler
@@mutex.synchronize do
handlers = @@handlers ||= [] of Int32, ::Exception? ->
handlers << handler
end
end

def self.run(status, exception = nil)
if handlers = @@handlers
# Run the registered handlers in reverse order
while handler = handlers.pop?
begin
handler.call status, exception
rescue handler_ex
Crystal::System.print_error "Error running at_exit handler: %s\n", handler_ex.message || ""
status = 1 if status.zero?
end
return status unless @@handlers

# Run the registered handlers in reverse order
while handler = @@mutex.synchronize { @@handlers.try(&.pop?) }
begin
handler.call status, exception
rescue handler_ex
Crystal::System.print_error "Error running at_exit handler: %s\n", handler_ex.message || ""
status = 1 if status.zero?
end
end

Expand Down