Max*_*xM. 4 python multithreading termination
我尝试使用geeksforgeeks 的
不同方法来获取示例 1在 python 线程中引发异常来终止正在运行的线程。PyThreadState_SetAsyncExc()
但由于某种原因,线程没有终止。
我用的是python3.6
这是源代码
# Python program raising
# exceptions in a python
# thread
import threading
import ctypes
import time
class thread_with_exception(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
# target function of the thread class
try:
while True:
print('running ' + self.name)
finally:
print('ended')
def get_id(self):
# returns id of the respective thread
if hasattr(self, '_thread_id'):
return self._thread_id
for id, thread in threading._active.items():
if thread is self:
return id
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(2)
t1.raise_exception()
t1.join()
Run Code Online (Sandbox Code Playgroud)
有人知道为什么线程没有因 raise 信号而终止吗?
换thread_id行为ctypes.c_long:
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(thread_id),
ctypes.py_object(SystemExit))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1762 次 |
| 最近记录: |