Fix race condition on shutdown