correctly handle multithread exit