Implement a shutdown mechanism that runs a function when the main thread exits.