family, type, proto, _, sockaddr = addr_info[0]
sock = socket.socket(family, type, proto)
sock.bind((host, port))
+ sockname = sock.getsockname()
thread = threading.Thread(target=lambda: echo_datagrams(sock))
thread.start()
try:
- yield sock.getsockname()
+ yield sockname
finally:
- sock.sendto(b'STOP', sock.getsockname())
+ # gh-122187: use a separate socket to send the stop message to avoid
+ # TSan reported race on the same socket.
+ sock2 = socket.socket(family, type, proto)
+ sock2.sendto(b'STOP', sockname)
+ sock2.close()
thread.join()