Ref: the chat example from the asyncnet module
I was wondering how resilient is the var clients and associated iterator to changes whils the loop for sending to each peer was still running.
After experimenting a bit as per https://gist.github.com/LucaWolf/0ea7a06a8224136fc1a54cabbb434fc6, it turns out the clients iterator deals happily with async changes to the base variable. Not very sure I undestand why it works but it just does. I could not fault it even when trying to remove clients registered before and after the active braodcaster (plus adding new clients).
Would be nice if someone knowledgeable of the inner workings of iterators and await could conform that no additional locking mechanism is required.
Thank you.
Keep in mind that async procedures are executed until an await (or yield), always. If you're mutating a hash table inside an async procedure there is no risk of problems, because the function won't yield to another function during the mutation.
If you add parallelism into the mix via spawn and the like, then you will need to worry. But if you're only using async await you can feel pretty safe.
Thank you.
But I feel my choice of words has conveyed the wrong concern. I understand there is no true parallelism involved, so wasn't asking about the clients variable itself (which could be a table or a sequence or whatever, depending on the implementation) but more about the iterator context. Let's consider this flow:
# proc processClient:
# ...
for x in items of clients:
await reply to x # dispatcher control
# label_a
await sleepAsync (10000) # exacerbate demo: dispatcher awakes serve as new client accepted
#proc serve:
new connection arives and gets registered # clients is modified
await sleepAsync(15000) # this passes control back to the dispatcher.
# when the 10 sec of processClient elapsed, the iterator is resurected and
# the flow resumes at (I'd assume) label_a.
Question: how is the encapsulating iterator's context aware of the boundary change of the variable it iterates over? [ assuming there is some context recovery ]