0

I'm trying to run a while True loop with asyncio.

import asyncio

async def cpu_bound_task():
    something that take long time
    return result

async def post_result_from_cpu_bound_task(res):
    _loop = asyncio.get_event_loop()
    post_res = await _loop.run_in_executor(
        None,
        request.post,
        end_point,
        data
    )

async def main():
    while True:
        cpu_task = asyncio.create_task(cpu_bound_task())
        res = await cpu_task
        post_result_task = asyncio.create_task(post_result_from_cpu_bound_task(res))
        r = await post_result_task

asyncio.run(main())

What I expect is

  1. do cpu task
  2. and it return result as res
  3. pass res to coroutine that post res
  4. while posting the res do cpu task asynchronously
  5. when cpu task is done, the post task that run asynchronously with cpu task would be done too
  6. go to phase 2

but its actual workflow is

  1. do cpu task
  2. and it return result as res
  3. pass res to coroutine that post res
  4. post task is done
  5. go to phase 1

The Python version I'm using is 3.10.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
humanlearning
  • 63
  • 1
  • 6
  • 2
    Your code `r = await post_result_task` quite literally means "post task is done; go to phase 1". So don't wait for `post_result_task` to be done by removing `await post_result_task`. – mkrieger1 Jun 08 '23 at 15:43
  • Does this answer your question? [How can I call an async function without await?](https://stackoverflow.com/questions/44630676/how-can-i-call-an-async-function-without-await) – mkrieger1 Jun 08 '23 at 15:51
  • @mkrieger1 I remove the code line that you said with adding print("would this really be executed?") in post function and when I run that there was not any error with printing "would this really be executed?" and I realize that I really don't know about async/await so would you share any document that explain await well? besides, if I want the result from request.post, what should I do? – humanlearning Jun 09 '23 at 02:04

0 Answers0