在python中如何在同一对象内生成另一个线程?

2024-04-19 03:48:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是装有Cygwin的vanilla Python2.7

我希望能够生成一个调用顶级函数的线程子类,而顶级函数生成调用子级函数的单独线程。这是伪代码

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?

Tags: theto函数selftargetdeffunctionpass
2条回答

有很多方法可以做到这一点,我最熟悉线程池,它们有一个非常简单的接口来调用线程和连接它们。。。

from multiprocessing.pool import ThreadPool

# This is the top level function called by other objects
def reboot(self):
    # setup your thread pool:
    reboot_pool = ThreadPool()
    # - First thread calls the __powerDown() function
    power_down = reboot_pool.apply_async(self.__powerDown())
    # this will block until it finishes
    power_down.get()
    # - Secod thread calls the __powerUp() function
    power_up = reboot_pool.apply_async(self.__powerUp())
    #   block until __powerUp() thread finishes
    power_up.get()

def __powerDown(self):
    # What to put here?
    pass

def __powerUp(self):
    # What to put here?
    pass

它与你所说的略有不同,因为首先我调用powerDown,等待它完成,然后调用powerUp,但我认为它完成了这个想法。

像这样的?

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

相关问题 更多 >