2013-09-24 36 views
2

我正在使用加載Cygwin的香草Python 2.7我想要能夠產生調用頂級函數的線程子類,並且頂級函數會生成單獨的線程來調用子級函數。下面是僞代碼如何在python中的同一對象中的另一個線程內產生一個線程?

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? 
+0

其實我的代碼有一個錯誤(缺少'target'關鍵字)。請現在查看代碼,因爲您的編輯不正確(它正在調用函數而不是將它傳遞給線程)。 – freakish

回答

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 
+0

如何將您的解決方案擴展到三個線程?也就是1)啓動__powerDown線程,完成時,2)啓動__doSomething線程,完成時,3)啓動__powerUp線程 –

0

有很多方法可以做到這一點,我最熟悉的線程池,他們有調用線程,並加入他們一個非常簡單的界面...

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,但是我認爲它完成了這個想法。

+0

ThreadPool構造函數的initializer和initargs值應該是什麼? –

+0

你不需要給它任何東西,但如果需要的話,你可以給它一個processes =參數。查看ProcessPool構造函數的文檔,它完全一樣。 –

+0

我這樣做,它確實抱怨沒有足夠的參數傳遞給construnctor –

相關問題