簡體   English   中英

在python的同一文件中創建Thread類的實例?

[英]Create instance of a Thread class within the same file in python?

我正在嘗試在同一文件的類B中創建一個名為AThread類型類的實例。

我嘗試了一些組合x = A(i)x = AA(i)x = A.__init(i)等等...

from threading import Thread

class A(Thread):
    def __init__(self, i)
        Thread.__init__(self)
        self.i = i

    def run(self):
        print('foo')

class B()
    def __init__(self):
        x = #instance of A ?
        x.start()

if __name__ == '__main__':
    B() # Here I call the class B that should start the thread of A

我需要給全班打電話。 而不是類內部的方法。 因為我想然后調用x.start()方法來啟動線程。

您可以像顯示的那樣調用x.start() 只需確保從B.__init__調用x.join() -這是主線程。 通常,您希望主線程在所有子線程上“等待”或“加入”。 這是一個工作示例:

>>> from threading import Thread
>>> import time
>>>
>>> class A(Thread):
...
...    def __init__(self, i):
...        Thread.__init__(self)
...        self._index = i
...        
...    def run(self):
...        time.sleep(0.010)
...        for i in range(self._index):
...            print('Thread A running with index i: %d' % i)
...            time.sleep(0.100)
...            
>>>
>>> class B(object):
...    
...    def __init__(self, index):
...        x = A(i=index)
...        print ('starting thread.')
...        x.start()
...        print('waiting ...')
...        x.join()
...        print('Thread is complete.')
...        
>>> if __name__ == '__main__':
...    B(10) # Here I call the class B that should start the thread of A
starting thread.
waiting ...
Thread A running with index i: 0
Thread A running with index i: 1
Thread A running with index i: 2
Thread A running with index i: 3
Thread A running with index i: 4
Thread A running with index i: 5
Thread A running with index i: 6
Thread A running with index i: 7
Thread A running with index i: 8
Thread A running with index i: 9
Thread is complete.

最后要注意的是,沒有理由A.__init__不能對其本身調用start() (而不是B.__init__這樣做),這只是樣式問題。 唯一真正關鍵的是,主線程在最佳實踐中應等待或加入所有子線程-如果不這樣做,則在某些應用程序中會出現奇怪的行為,因為主線程先於子線程退出。 看到這個:

更多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM