Search code examples
pythonmultithreadingpython-multithreading

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

Solution

  • 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)