博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python动态线程_python在动态中杀(停止)子线程的方法
阅读量:6973 次
发布时间:2019-06-27

本文共 1945 字,大约阅读时间需要 6 分钟。

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 线程 杀 动态

转载地址:http://oxhsl.baihongyu.com/

你可能感兴趣的文章
Html5拖拽复制
查看>>
RDLC报表格式化format表达式
查看>>
ArcMap属性的列菜单简介
查看>>
【2011.9.20】基于CXF Web Service:Apache CXF简单部署 .
查看>>
jquery Flexigrid的使用
查看>>
Inotify + rsync
查看>>
中风从水治案
查看>>
SQL Server 内存使用量下降问题
查看>>
嵌入式驱动开发之dsp fpga通信接口---spi串行外围接口、emif sram接口
查看>>
网络协议之socks---子网和公网的穿透
查看>>
Java控制语句——if语句
查看>>
BadUSB的防范研究
查看>>
网站flash黑屏问题
查看>>
JAVA TIMER定时器
查看>>
CCF-201512-3 绘图
查看>>
测试了一下LINQ写的Quick Sort性能
查看>>
网站是否有播放音乐功能
查看>>
架构设计:远程调用服务架构设计及zookeeper技术详解(上篇)
查看>>
41、java与mysql乱码的问题
查看>>
细说 Form (表单)
查看>>