Fix thread shutdown race