" RuntimeError:thread .__ init __()未称为“;当子类化threading.Thread时 [英] " RuntimeError: thread.__init__() not called" when subclassing threading.Thread
问题描述
我需要运行与列表目录中的元素一样多的Observer类线程. 当我运行它的python控制台时,它可以正常工作.
I need to run as many threads of class Observer as there are elements in list dirlist. When I run it python console it works all right.
class Observer(Thread):
def run(self):
naptime = random.randint(1,10)
print(self.name + ' starting, running for %ss.' % naptime)
time.sleep(naptime)
print(self.name + ' done')
observers = {}
for d in dirlist:
observers[d] = Observer()
observers[d].start()
但是,当我尝试从应该生成观察者线程的主线程执行此操作时,我会出错.
But when I try to do it from a Master thread which is supposed to spawn the Observer threads I get errors.
class Master(Thread):
def __init__(self, dirlist):
self.dirlist = dirlist
def run(self):
observers = {}
for d in dirlist:
observers[d] = Observer()
observers[d].start()
while True:
time.sleep(3600)
master_thread = Master(dirlist)
master_thread.start()
对Master.start
的调用导致:
RuntimeError: thread.__init__() not called
这对我来说很奇怪.
我无法理解这两种情况之间的区别.
有人可以找出解决我问题的方法吗?
This looks strange to me.
I am unable to understand whats the difference between both cases.
Can anybody figure out a solution to my problem ?
以某种方式的跟踪不会产生错误,我也不明白为什么.
Somehow following doesn't produce an error, and I don't understand why.
class Master(Thread):
def set(self, dirlist):
self.dirlist = dirlist
def run(self):
observers = {}
for d in dirlist:
observers[d] = Observer()
observers[d].start()
while True:
time.sleep(3600)
master_thread = Master()
master_thread.set(dirlist)
master_thread.start()
推荐答案
>>> master_thread.start()
RuntimeError: thread.__init__() not called
请确保在您的Master.__init__
中呼叫Thread.__init__()
:
class Master(Thread):
def __init__(self, dirlist):
super(Master, self).__init__()
self.dirlist = dirlist
这篇关于" RuntimeError:thread .__ init __()未称为“;当子类化threading.Thread时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!