2013-04-02 100 views
0

我有一個線程類,在其中,我想創建一個線程函數來更正線程實例的工作。如果是的話,有可能如何?線程類實例創建一個線程函數

線程類的運行函數正在每一個興奮地工作x秒。我想創建一個線程函數來執行與運行函數並行的工作。

class Concurrent(threading.Thread): 
    def __init__(self,consType, consTemp): 
      # something 

    def run(self): 

      # make foo as a thread 

    def foo (self): 
      # something 

如果不是,想想下面的情況,可以嗎,怎麼樣?

class Concurrent(threading.Thread): 
    def __init__(self,consType, consTemp): 
      # something 

    def run(self): 

      # make foo as a thread 

def foo(): 
    # something 

如果不清楚,請告訴。我會嘗試reedit

回答

0

只需啓動另一個線程。您已經知道如何創建它們並啓動它們,因此只需編寫Threadstart()的另一個子文件夾即可。

更改def foo()代替Thread子類與run()代替foo()

+0

如果可以,你可以給我expilicit答案。 (英語不是我的母語,我不太明白) – user2229183

0

首先,我建議你會重新考慮使用線程。在Python中的大多數情況下,您應該使用multiprocessing來代替。這是因爲Python的GIL
除非你使用JythonIronPython ..

如果我理解正確的話,只要打開你已經打開的線程中的另一個線程:

import threading 


class FooThread(threading.Thread): 
    def __init__(self, consType, consTemp): 
     super(FooThread, self).__init__() 
     self.consType = consType 
     self.consTemp = consTemp 

    def run(self): 
     print 'FooThread - I just started' 
     # here will be the implementation of the foo function 


class Concurrent(threading.Thread): 
    def __init__(self, consType, consTemp): 
     super(Concurrent, self).__init__() 
     self.consType = consType 
     self.consTemp = consTemp 

    def run(self): 
     print 'Concurrent - I just started' 
     threadFoo = FooThread('consType', 'consTemp') 
     threadFoo.start() 
     # do something every X seconds 


if __name__ == '__main__': 
    thread = Concurrent('consType', 'consTemp') 
    thread.start() 

程序的輸出將是:

併發 - 我剛剛開始
FooThread - 我剛剛開始

相關問題