线程:断言错误:组参数现在必须为 None

Sah*_*and 3 python multithreading

这是可停止线程的实现以及使用它的尝试:

import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""
    def __init__(self, target, kwargs):
        super(StoppableThread, self).__init__(target, kwargs)
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.it_set()

def func(s):
    print(s)

t = StoppableThread(target = func, kwargs={"s":"Hi"})
t.start()
Run Code Online (Sandbox Code Playgroud)

此代码会生成错误:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    t = StoppableThread(target = func)
  File "test.py", line 7, in __init__
    super(StoppableThread, self).__init__(target)
  File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 780, in __init__
    assert group is None, "group argument must be None for now"
AssertionError: group argument must be None for now
Run Code Online (Sandbox Code Playgroud)

我想知道为什么以及如何解决它。

gal*_*yan 6

线程的第一个参数是组,因此您需要为目标提供名称

super(StoppableThread, self).__init__(target=target, kwargs)
Run Code Online (Sandbox Code Playgroud)

有文件

类 threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

https://docs.python.org/2/library/threading.html#threading.Thread