How to spawn a thread inside another thread in the same object in python?
10,170
Something like this?
import threading
class Server(threading.Thread):
# some code
# This is the top level function called by other objects
def reboot(self):
# perhaps add a lock
if not hasattr(self, "_down"):
self._down = threading.Thread(target=self.__powerDown)
self._down.start()
up = threading.Thread(target=self.__powerUp)
up.start()
def __powerUp(self):
if not hasattr(self, "_down"):
return
self._down.join()
# do something
del self._down
Author by
Chris F
I'm a professional software developer by day, dad/husband by night, and a performing musician on some weekends. I love ALL DevOps - it's not a job, it's my passion!
Updated on June 13, 2022Comments
-
Chris F almost 2 years
I'm using vanilla Python 2.7 loaded with Cygwin
I want to be able to spawn a thread subclass that calls a top-level function, and the top-level function spawns separate threads calling sub-level functions. Here's pseudo-code
import threading #!/usr/bin/python import threading class Server(threading.Thread): def __init__(self, threadID, target): self.__threadID = threadID self.__target = target threading.Thread.__init__(self) # Function called when the thread's start() function is called def run(self): self.target() pass # This is the top level function called by other objects def reboot(self): # I want this function to spawn two threads # - First thread calls the __powerDown() function # - Secod thread calls the __powerUp() function, and pends # until __powerDown() thread finishes pass def __powerDown(self): # What to put here? pass def __powerUp(self): # What to put here? pass __threadID = '' __target = None # Code calling above code server = Server(123, reboot) # Will this work?