Search code examples
pythonmultithreadingthread-sleep

Python time.sleep lock process


I want to create multi process app. Here is sample:

import threading
import time
from logs import LOG


def start_first():
    LOG.log("First thread has started")
    time.sleep(1000)


def start_second():
    LOG.log("second thread has started")


if __name__ == '__main__':
    ### call birhtday daemon
    first_thread = threading.Thread(target=start_first())

    ### call billing daemon
    second_thread = threading.Thread(target=start_second())

    ### starting all daemons
    first_thread.start()
    second_thread.start()

In this code second thread does not work. I guess, after calling sleep function inside first_thread main process is slept. I found this post. But here sleep was used with class. I got that(Process finished with exit code 0 ) as a result when I run answer. Could anybody explain me where I made a mistake ?

  • I am using python 3.* on windows

Solution

  • When creating your thread you are actually invoking the functions when trying to set the target for the Thread instead of passing a function to it. This means when you try to create the first_thread you are actually calling start_first which includes the very long sleep. I imagine you then get frustrated that you don't see the output from the second thread and kill it, right?

    Remove the parens from your target= statements and you will get what you want

    first_thread = threading.Thread(target=start_first)
    second_thread = threading.Thread(target=start_second)
    first_thread.start()
    second_thread.start()
    

    will do what you are trying