在python中的同一文件中创建Thread类的实例?

时间:2015-03-04 15:19:49

标签: python multithreading

我正在尝试在同一文件中的类Thread中创建名为A的{​​{1}}类型类的实例。

我尝试了一些组合Bx = A(i)x = A.A(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 方法来启动线程。

1 个答案:

答案 0 :(得分:0)

您可以像展示一样致电x.start()。只需确保从x.join()致电B.__init__ - 这是主线索。通常,您希望主线程在所有子线程上“等待”或“加入”。这是一个有效的例子:

>>> 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__执行此操作) - 这只是一种风格问题。唯一真正关键的是主线程应该在最佳实践中等待或加入所有子线程 - 如果你不这样做,你可以在某些应用程序中获得奇怪的行为,因为主线程在子线程之前退出。见:

了解更多。