-1

I am trying to run two infinitely looping functions concurrently and will later implement this into a socket chatroom application for each client that is connected to my server. The problem is, whenever the function that I am trying to gather is run in an infinite while loop, my program will only run the first function that is gathered.

Here is my code:


async def increment():

    global money

    while True:
        money += 1



async def displayMoney():

    global money

    while True:
        input(money)



async def main():

    global money

    await asyncio.gather(increment(), displayMoney())



asyncio.run(main())

I am new to asynchronous programming, apologies.

1

1 Answer 1

0

If you add await asyncio.sleep(0) at the end of the loop, it allows the loops to give each other time to run. However, this means you cannot run anything that stops the main event loop, such as time.sleep(1) or input(), like I was trying to do. This is fine though as I do not need to use any of these in my main program as it utilises tkinter gui.

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

2 Comments

Note that using await asyncio.sleep(0) to force a context switch is somewhat of a code smell. Asyncio is primarily for IO-based parallelism, so an asyncio coroutine is expected to await something IO-related (or a synchronization device like a queue) sooner or later. If you really need to run something blocking or CPU-heavy, use await loop.run_in_executor(None, fn, args...).
@user4815162342 what does this code do sorry?

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.