Fix potential crash in terminate_threads()