0
queue = []

async def funcA():
    r = random.randint(0, 1000)
    i = 0
    for i in range(10000000):
        pass
    print(r)
    queue.append(r)

    asyncio.create_task(funcb(r))

async def funcb(r):
    i = 0
    for i in range(100000000):
        pass
    print(r, "XX")
    queue.pop()


async def main():
    for i in range(10):
        await funcA()
    print(queue)


if __name__ == "__main__":
    asyncio.run(main())

How do I make funcb() run simultaneously? In this code funcb() runs only after all calls of funcA() are done executing. I want funcB() to run concurrently with funcA() (on same or different threads). Here if funcA() runs infinitely, then funcB() would never run.

3
  • 3
    They’re both blocking functions, they don’t yield/await anything internally. Even if you start them together, they can only be executed one after the other. For parallel execution, you need threading. Commented Aug 28, 2021 at 7:57
  • You might be able to use run_in_executor but as other people say this isn't something you really want to do with asyncio Commented Aug 28, 2021 at 11:44
  • Wouldn't mind hearing back from you and getting a checkmark if you found my answer helpful. Commented Sep 6, 2021 at 22:16

1 Answer 1

4

Asyncio is a so-called non-preemptive task scheduler.

This means, it cannot switch back and forth between tasks on its own, it requires the function it is calling to actively give up (=yield) the priority.

As your function is not asynchronous (= doesn't have any commands in it that would wait for something with the await keyword), it just runs to completion before yielding back to the asyncio scheduler.

The way you described your problem sounds like it isn't really suitable for asynchronous programming, but instead requires multithreading or even multiprocessing (if you desire to get a speedup from the 'simultaneous' computing).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.