2013-09-24 37 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 –

相关问题