Fix a possible race when stopping threads.