2

Cygwinを搭載したバニラPython 2.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?
4

2 に答える 2

2

このようなもの?

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
于 2013-09-24T19:02:47.157 に答える
0

これを行う方法はたくさんありますが、私は ThreadPools に最も精通しており、スレッドを呼び出して参加するための非常に簡単なインターフェイスを備えています...

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を呼び出すため、あなたが述べた方法とは少し異なりますが、アイデアは完成すると思います。

于 2013-09-24T18:47:01.980 に答える