Search code examples
pythonmultithreadingpython-daemon

Python multi-threading: How to keep daemon thread running


I'm stuck at a tricky problem to test whether a daemon thread is running. The daemon thread I made should run at the background to keep the service running, so I do the following to create it and keep it alive:

Creation:

ASThread = threading.Thread(target = initAirserv, args=[],)
ASThread.setDaemon(True)
ASThread.start()

Inside the initAirserv() method:

def initAirserv(self, channel="15"):
        interface = self.execAirmon(options="start", interface=self.interface)
        port = self.plug_port
        if interface != "removed":
            if channel=="15":
                command = "airserv-ng -d " +str(interface)+" -p "+str(port)
            else:
                command = "airserv-ng -d " +str(interface)+" -p "+str(port)+" -c"+str(channel)
        else:
            return None
        AServConn=self.init_Plug()
        if AServConn:
            (stdin, stdout, stderr) = AServConn.exec_command(command)
            serv_op = stdout
            serv_er = stderr
            ##### keep the daemon thread run persistently ####
            a = 0 
            while 1:
                a += 1
        else:
            logging.debug( "SSH Error" )

The purpose of the last several lines is to keep the thread busy using a stupid way. However, after starting this daemon thread and I did something else, when I came back and check the thread as follows:

if ASThread.is_alive() == 1:
    # do something

the if body never gets executed. Can someone explain to me why does this happen? What's the best way to run a thread which executes something that needs to be busy all the time? Thanks very much.


Solution

  • The posted code doesn't add up. initAirserv as posted is a method on a class, but the initAirserv passed to the Thread constructor is not.

    It's also hard to say anything concrete without knowing what execAirmon and init_Plug does, and what else happens in your application.

    In general, I'd say you have it right. This should work. The fact that it doesn't means your assumptions are wrong.

    • Are you sure execAirmon returns something that is not equal to "removed"?
    • Are you sure init_Plug returns a non-false object?
    • Are you sure no exceptions are thrown? (I assume you would notice a spurious stacktrace, so are there other parts of your application that could swallow them up unnoticed?)