Here's an implementation of a stoppable thread and an attempt at using it:
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()
This code generates an error:
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
I would like to know why and how to fix it.
the first argument for thread is group, thus you need give name for target
super(StoppableThread, self).__init__(target=target, kwargs)
there is document
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
https://docs.python.org/2/library/threading.html#threading.Thread
Try the following:
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, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = Event()
The *args
is a sequence with every positional argument and **kwargs
is a dictionary with every key-wrod argument. By using this notation you are passing every argument that you pass to the StoppableThread
constructor to its parent. The names of the vars *args
and **kwargs
are arbitrary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.