Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用抛出异常方法(Python)终止线程_Python_Multithreading_Exception - Fatal编程技术网

如何使用抛出异常方法(Python)终止线程

如何使用抛出异常方法(Python)终止线程,python,multithreading,exception,Python,Multithreading,Exception,我在网上发现了一些代码,这些代码在等待一段时间后会通过异常停止线程 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_SetA

我在网上发现了一些代码,这些代码在等待一段时间后会通过异常停止线程

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\u异常,不如在线程的run方法内调用它。前

def run(self):
    if count>3:
         self.raise_exception()

与其在类外调用raise_异常,不如在线程的run方法内调用它。前

def run(self):
    if count>3:
         self.raise_exception()