Fix deadlock and clean shutdown.