Example 1-StackOverflow:
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):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
Example 2-适用于实验室的Python:
class OhmLaw:
def __init__(self):
self.data = np.zeros(0) # To store the data of the measurement
self.step = 0 # To keep track of the step
self.running = False
self.stop = False
def make_measurement(self, start, stop, num_points, delay):
# left out additional code to keep example simple.
for i in x_axis:
if self.stop:
print('Stopping')
break
问题:
是否正在使用boolean
来取消thread
的不良习惯?是使用Event.set()
的首选方法吗?
使用boolean
进行取消是否有不利之处?
来自docs:
将内部标志设置为true。所有等待它成为的线程 真实被唤醒。一旦标记为true,则调用wait()的线程将 完全不会阻塞。
我认为不能单独使用boolean
来完成此操作,但是该文档适用于跨多个线程共享的event
对象,我不认为您会使用{ {1}}。