Prevent race condition in example code (#305)

The example async server code uses timeouts around read() operations.
However, this has a race condition where data can be read, the timeout
fires, and the data is lost.

These timeouts are not really needed in this example code, so I removed
them to prevent people from having strange issues with lost messages
and undefined RPC behavior when using the example code.
This commit is contained in:
André Cruz 2023-01-09 06:29:23 +00:00 committed by GitHub
parent 9b6ff51f9c
commit 1b19b6db13
Failed to generate hash of commit

View file

@ -550,35 +550,21 @@ To simplify the callbacks use a server class to define the reader/writer callbac
class Server:
async def myreader(self):
while self.retry:
while self.retry and not self.reader.at_eof():
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.reader.read(4096),
timeout=0.1
)
except asyncio.TimeoutError:
print("myreader timeout.")
continue
data = await self.reader.read(4096)
await self.server.write(data)
except Exception as err:
print("Unknown myreader err: %s", err)
return False
await self.server.write(data)
print("myreader done.")
return True
async def mywriter(self):
while self.retry:
try:
# Must be a wait_for so we don't block on read()
data = await asyncio.wait_for(
self.server.read(4096),
timeout=0.1
)
data = await self.server.read(4096)
self.writer.write(data.tobytes())
except asyncio.TimeoutError:
print("mywriter timeout.")
continue
except Exception as err:
print("Unknown mywriter err: %s", err)
return False