" AssertionError:Thread .__ init __()未调用"初始化threading的子类时.Thread

时间:2016-11-01 17:53:37

标签: python multithreading

我想创建一个运行两个线程的程序,可以使用 ctrl + C 同时中断。以下脚本是此的简化版本:

import time
import threading

class Controller(object):
    def __init__(self, name=None):
        self.name = name

    def run_once(self):
        print("Controller {} is running once...".format(self.name))

    def run_forever(self):
        while True:
            self.run_once()
            time.sleep(1)

if __name__ == "__main__":
    controller1 = Controller(name="1")
    controller2 = Controller(name="2")
    thread1 = threading.Thread(target=controller1.run_forever)
    thread2 = threading.Thread(target=controller2.run_forever)
    thread1.daemon = True
    thread2.daemon = True
    thread1.start()
    thread2.start()


    try:
        while True:
            thread1.join(1)
            thread2.join(1)
            if not thread1.isAlive() or not thread2.isAlive():
                break
    except KeyboardInterrupt:
        pass

我尝试通过执行以下操作使代码更加干燥:

import time
import threading

class Controller(object):
    def __init__(self, name=None):
        self.name = name

    def run_once(self):
        print("Controller {} is running once...".format(self.name))

    def run_forever(self):
        while True:
            self.run_once()
            time.sleep(1)

class ThreadController(Controller, threading.Thread):
    def __init__(self, *args, **kwargs):
        Controller.__init__(self, *args, **kwargs)
        threading.Thread.__init__(self, target=self.run_forever)
        self.daemon = True
        self.start()


if __name__ == "__main__":
    thread1 = ThreadController(name="1")
    thread2 = ThreadController(name="2")

    try:
        while True:
            thread1.join(1)
            thread2.join(1)
            if not thread1.isAlive() or not thread2.isAlive():
                break
    except KeyboardInterrupt:
        pass

但是,当我尝试运行后一个脚本时,我收到以下错误:

Traceback (most recent call last):
  File "threading_test3.py", line 34, in <module>
    thread1 = ThreadController(name="1")
  File "threading_test3.py", line 18, in __init__
    Controller.__init__(self, *args, **kwargs)
  File "threading_test3.py", line 6, in __init__
    self.name = name
  File "/usr/lib/python2.7/threading.py", line 971, in name
    assert self.__initialized, "Thread.__init__() not called"
AssertionError: Thread.__init__() not called

我不明白为什么Thread.__init__()没有被调用,因为它似乎是在__init__ ThreadController中调用的。导致此错误的原因是什么?

1 个答案:

答案 0 :(得分:1)

首先调用线程的init;

""