Issue
I'm trying to update a variable's value in an infinite loop. a demo code of my situation is like this:
import asyncio, random
async def coro1():
await asyncio.sleep(random.randint(1,5))
global x
x = 5
async def coro2():
await asyncio.sleep(random.randint(1,5))
global x
x = 10
async def main():
global x # Edit
x = 1
while True:
async with asyncio.TaskGroup() as tg:
tg.create_task(coro1())
tg.create_task(coro2())
asyncio.run(main())
my goal is to update x
after all tasks are finished in an infinite loop.
Solution
how to assign a task result to variable while task is not finished yet
You don't - it really have to be finished so you get a result.
Of course, there is a problem with your question - if it is an infinite loop, there won't be a moment when "all tasks are finished".
There are usually two ways of working with this: if the code following the creation of the task will need to consume the result, then it is time to await
the task: Python will execute other concurrent tasks until this one is done, and the result will be returned, as far as the current code is concerned, as the result of the await
expression.
The other way is to add a "done callback" to your task. If you want to group tasks, then you should gather then with a call to asyncio.gather
, for example, and call .add_done_callback
on that. I don't think taskgroups as they are, have a way for one to schedule a callback when the task group is exited. In this case, the obvious way to code it is to simply call your desired code after closing the with
block for the task group.
(Of course, as I mentioned, this example is a bit confuse - but it would run the "after" code after each cycle of all tasks: )
async def main():
global x # This is missing in your example
x = 1
while True:
async with asyncio.TaskGroup() as tg:
tg.create_task(coro1())
tg.create_task(coro2())
x = 42 # this line will run after all tasks in the group
# above are done. Since it is an infinite loop,
# they will just start again
return # and this line (not needed, just added for illustrative purposes) is just reached when something breaks the infinite loop.
Answered By - jsbueno
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.