I'm going through Trio tutorial and I made an echo-client that sends message to an echo server for 10 seconds:
async def sender(client_stream, flag):
print("sender: started!")
end_time = time.time() + 10
while time.time() < end_time:
data = b"async can sometimes be confusing, but I believe in you!"
print("sender: sending {!r}".format(data))
await client_stream.send_all(data)
await trio.sleep(0)
flag = False
print("Left the while 10 seconds loops")
and wait for responses while the flag
is `True.
async def receiver(client_stream, flag):
print("receiver: started!")
while(flag):
data = await client_stream.receive_some()
print("receiver: got data {!r}".format(data))
print("receiver: connection closed")
sys.exit()
The problem is that sometimes the program hangs at line data = await client_stream.receive_some()
because of concurrency issues with regards to the variable flag
.
How do I send a signal from the sender
co-routine to the receiver
co-routine?
Here is the entire program that you can run.
It doesn't just sometimes hang there, it hangs all the time because the
flag
variable inreceiver()
never gets changed. I think you're under the impression that it's somehow shared betweenreceiver()
andsender()
. It's not.The simplest way you could fix that is by passing it in a container:
A more elegant solution would be closing the stream in
sender()
and catchingClosedResourceError
inreceiver()
:Notice how you don't even need
sys.exit()
for the program to end.