Angelina
Angelina

Reputation: 11

Adding a Time delay in code without time.sleep (code contains threading)

PSA: I'm a new coder

My goal is to run multiple functions simultaneously using threading. Each function currently has several time.sleep because I need gaps between the many steps taking place. But if I use time.sleep then the functions don't run simultaneously. Is there anything else that I can use instead of sleep to create the pauses in my code, which doesn't cause the thread to suspend?

To clarify, I don't want the thread to wait, I need to add waits within the functions.

Basic code that resembles the actual program I need to write:


def saysHi():
    time.sleep(5)
    print("\nHi")

def saysBye():
    time.sleep(5)
    print("\nBye")


if __name__ == "__main__":
    threading.Thread(target=saysHi()).start()
    # starting thread 2
    threading.Thread(target=saysBye()).start()

Upvotes: 1

Views: 1797

Answers (1)

Maurice Meyer
Maurice Meyer

Reputation: 18106

You are calling the functions when passing to the Thread constructor:

threading.Thread(target=saysHi()).start()

To make them run simultaneously, you just pass the function as argument to Thread constructor:

import threading, time


def saysHi():
    print("starting h1")
    time.sleep(5)
    print("\nHi")

def saysBye():
    print("starting bye")
    time.sleep(5)
    print("\nBye")


if __name__ == "__main__":
    threading.Thread(target=saysHi).start()  # saysHi is not called, just passed!
    threading.Thread(target=saysBye).start()

Out:

starting h1
starting bye


Hi

Bye

Upvotes: 1

Related Questions