Updated to avoid some race conditions and also to not try to spawn a thread if we are already in one.