python动态线程_python在动态中杀(停止)子线程的方法

这篇博客介绍了如何在Python中动态地停止子线程,使用了`_async_raise`函数结合`SystemExit`异常来实现。示例中创建了多个无限循环的线程,并在主线程中通过线程名识别并停止特定线程。关键在于子线程需要捕获`SystemExit`异常并调用`sys.exit()`以确保线程能被正确终止。
摘要由CSDN通过智能技术生成

import inspect

import ctypes

import time

import random

import traceback

from threading import Thread

import sys

# from utils.thread_killer import stop_thread

def _async_raise(tid, exctype):

"""raises the exception, performs cleanup if needed"""

tid = ctypes.c_long(tid)

if not inspect.isclass(exctype):

exctype = type(exctype)

res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,

ctypes.py_object(exctype))

if res == 0:

raise ValueError("invalid thread id")

elif res != 1:

# """if it returns a number greater than one, you're in trouble,

# and you should call it again with exc=NULL to revert the effect"""

ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)

raise SystemError("PyThreadState_SetAsyncExc failed")

def stop_thread(thread):

print(f'\nt -> {thread}')

print(f'\nthread.ident -> {thread.ident}')

_async_raise(thread.ident, SystemExit)

def func1():

while True:

try:

print(f'func1\n')

time.sleep(2)

except SystemExit:

sys.exit()

except:

print(traceback.format_exc())

def func2():

while True:

try:

print(f'func2]\n')

time.sleep(1.3)

except SystemExit:

sys.exit()

except:

print(traceback.format_exc())

def func3():

try:

func1()

except SystemExit:

sys.exit()

except:

print(traceback.format_exc())

class Test(object):

def __init__(self):

pass

def engine(self):

thread_pool = []

t1 = Thread(target=func3, args=())

t2 = Thread(target=func2, args=())

thread_pool.append(t1)

thread_pool.append(t2)

for i in thread_pool:

i.start()

while True:

try:

time.sleep(3)

# for i in thread_pool:

# print(f'线程{i}的状态{i.is_alive()}\n')

# print(f'线程{i}的名字{i.name}\n')

# print(f'线程的方法{i.ident}\n')

# time.sleep(1)

for i in thread_pool:

print(type(i.name))

if i.name == 'Thread-1':

print(f'开始杀线程')

stop_thread(i)

time.sleep(3)

thread_pool.remove(i)

print(f'thread_pool -> {thread_pool}')

print(i.is_alive())

except:

pass

if __name__ == '__main__':

test_case = Test()

test_case.engine()

要注意一定要在预备被杀的线程中拦截SystemExit错误,然后sys.exit(),否则不能杀死该线程。

关键字:python 线程 杀 动态

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值