Search code examples
pythonmultithreadingpython-multithreading

How to start threads with a delay in python


I created threads, added delay in the function, but all threads are executing at the same time. Instead i want threads to start one by one. Is that possible ? Below is my code

from _thread import start_new_thread
import time

def mul(n):
    time.sleep(1)
    res = n * n
    return res    

while 1:
    m = input("Enter number ")
    t = input("Enter the number of times the function should be executed:")
    max_threads = int(t)
    for n in range(0, max_threads):
        start_new_thread(mul, (m,))

    except:
        pass
        print("Please type only digits (0-9)")
        continue


    print(f"Started {max_threads} threads.")


Solution

  • First of all, you added the delay inside the thread, causing it to pause after it started. Thus, you are starting all the threads one by one without delay and when each thread starts it waits 1 second before continuing.

    So if you want a specific delay - add after you start each thread, in the main thread.

    If you want each thread to start after the previous thread finished, you can do the following:

    import threading
    .
    .
    .
    for n in range(0, max_threads):
        t = threading.Thread(target = mul, args=(m,))
        t.start()
        t.join() # Waits until it is finished