J
J
jslby2020-11-23 08:48:30
Python
jslby, 2020-11-23 08:48:30

How to run a function indefinitely in Python?

Hello!
There is a code:

import asyncio
from random import randint

async def worker():
  if condition == False:
    return False
  await asyncio.sleep(randint(1,3))
  return True


How can this code be run asynchronously indefinitely, but with control over the number of simultaneous executions?
I mean that the function after execution is completed, and the same function is immediately called again. There is also a processing of a large array of data, and it is necessary to somehow control the number of simultaneously running functions (for example, 10). Recursion is not an option, because there will be memory leaks. If the function returns False, then the number of simultaneous executions will no longer be 10, but 9, and so on until all functions complete their work correctly. Is there any module for such an implementation?

With threads, this is quite simple - an infinite while True loop opens in each thread and that's it, but as I understand it, this approach in asynchronous programming is not correct, how to do it right?

Added:
The easiest way is to implement it like this:
import asyncio
from random import randint


async def worker(i):
  while True:
    await asyncio.sleep(randint(1,3))
    print(f'Worker #{i}')


loop = asyncio.get_event_loop()
futures = [loop.create_task(worker(str(i))) for i in range(5)]

loop.run_forever()

but I'm not sure how correct it is to let an asynchronous function into an infinite loop

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-11-23
@jslby

Infinite means to run inside . You can limit with the help . Only this moment is not clear "If the function returns False, then the number of simultaneous executions will no longer be 10, but 9", why 9, and not again 10? while True

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question