根据 thread id 停止一个线程

出自 https://github.com/Bogdanp/dramatiq/blob/master/dramatiq/middleware/threading.py#L62

thread_id = threading.get_ident()

 

 1 def _raise_thread_exception_cpython(thread_id, exception):
 2     exctype = (exception if inspect.isclass(exception) else type(exception)).__name__
 3     thread_id = ctypes.c_long(thread_id)
 4     exception = ctypes.py_object(exception)
 5     count = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, exception)
 6     if count == 0:
 7         logger.critical("Failed to set exception (%s) in thread %r.", exctype, thread_id.value)
 8     elif count > 1:  # pragma: no cover
 9         logger.critical("Exception (%s) was set in multiple threads.  Undoing...", exctype)
10         ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.c_long(0))

https://docs.python.org/3/c-api/init.html#c.PyThreadState_SetAsyncExc

posted @ 2019-03-18 09:47  两只老虎111  阅读(807)  评论(0编辑  收藏  举报