我在网上找到了一些代码,这些代码将在等待一段时间后通过异常停止线程。
def raise_exception(self):
thread_id = self.get_id()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
一段时间后,由以下人员调用异常:
t1 = thread_with_exception('Thread 1')
t1.start()
time.sleep(1/1000)
t1.raise_exception()
t1.join()
我想调用一个异常,该异常将指定进程发生的时间。如:
t1 = thread_with_exception('Thread 1')
t1.start()
if t1.count >= 3:
t1.raise_exception()
t1.join()
但是,当 t1.count>= 3 时,这无法调用异常。
不能以这种方式调用异常吗?
与其在
类外部调用raise_exception,不如从线程的 run 方法中调用它。 例如。
def run(self):
if count>3:
self.raise_exception()