wizarpy_vm
wizarpy_vm

Reputation: 426

Run function inside a loop without its stopping

I'd like to run the loop and return some value from the function with time.sleep() without interrupting the loop.

How to make the function and the loop work simultaneously?

The function prt_1 uses time.sleep(5). I'd like not to wait this time in the loop. I need the loop to keep running while the function is sleeping

import time

def prt_1(i):
    while True:
        print(f"AAA_{i}")
        time.sleep(5)

for i in range(100):
    print(i)
    prt_1(i)
    time.sleep(0.5)

to get something like that:

0
AAA_0
1
2
3
4
5
AAA_5

Upvotes: 0

Views: 562

Answers (2)

Blondberg
Blondberg

Reputation: 121

You could for instance look into 'asyncio' to create methods that can run concurrently.

This will do what you needed (if I understood it correctly)!

import asyncio

async def prt_1(i):
    while True:
        print(f"AAA_{i}")
        await asyncio.sleep(5)

async def main():
    for i in range(100):
        print(i)
        asyncio.create_task(prt_1(i))
        await asyncio.sleep(0.5)


asyncio.run(main())

Asyncio.create_task will call your function and let it run concurrently with the loop. And you also have to modify so the function is an 'async' function, and that the loop is also in one.

Upvotes: 1

Jona B
Jona B

Reputation: 36

This would be the answer you are looking for by placing each loop in a separate thread:

from threading import Thread
import time
def prt_1(i):
    while True:
        print(f"AAA_{i}")
        time.sleep(5)

for i in range(100):
    thread = Thread(target=prt_1, args=(i,))
    thread.start()
    time.sleep(0.5)

Upvotes: 1

Related Questions