Search code examples
pythonmultithreadingpython-2.7python-multithreadinglinux-mint

Why is my Daemon thread pausing the calling function's execution?


Please forgive me if my question's terminology is not quite correct; I am not a professional programmer.

This is the function my Daemon thread is calling:

def _pause_console(self, pause_time):
    print("pausing console")
    self.javaserver.server_muted = True
    print("muted")
    time.sleep(pause_time)
    print("unmuted")
    self.javaserver.server_muted = False

It is called by this code (all in the same class):

    pausetime = 30
    print("starting pause...")
    cm = threading.Thread(target=self._pause_console(pausetime), args=())
    cm.daemon = True
    cm.start()
    print("pause daemon thread started.")

The console output prints my print statements (30 second sleep being specified) in this order:

starting pause

pausing console

muted

unmuted

pause daemon thread started

I was expecting that "pause daemon.." would at least show up before 'unmuted'... I.e., that the main loop execution would continue after the thread was started. However, it appears (to me) that the 'cm.start()' must exit before the 'print("pause daemon thread started.")' statement is executed?

What am I doing wrong or where is my conceptual error here?

(hard to believe no one has encountered this before, but I can't seem to find similar questions on here)


Solution

  • Because your code immediately calls target function while constructing Thread object. You should replace it with following:

    cm = threading.Thread(target=self._pause_console, args=(pausetime,))