1

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
Community
  • 1
  • 1
Ulug'bek
  • 2,762
  • 6
  • 31
  • 59
  • it actually would run but your `time.sleep(1000)` in method 1 is so long that you have to wait for 1000 seconds, change it to `time.sleep(5)` to see the immediate results. – ZdaR May 25 '15 at 12:51
  • OK, but it blocks second thread. Why it works like that ? – Ulug'bek May 25 '15 at 12:53

1 Answers1

4

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

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • 2
    Also, if you want to create a thread for a function with parameters you can use `first_thread = threading.Thread(target=start_first, args = ())` – ZdaR May 25 '15 at 13:02