Socket: fix potential race condition