python结束线程_python终止线程

本文详细介绍了Python中结束线程的六种方法:通过抛出异常、设置终止标志、使用traces、多线程模型、将线程设置为守护进程以及利用隐藏属性_stop()。每种方法都有其适用场景和注意事项,比如使用异常终止可能导致资源未释放,而设置守护进程则会在主程序退出时自动结束线程。
摘要由CSDN通过智能技术生成

可以通过以下方式来终止线程:通过抛出异常来终止进程

通过一个终止标志来终止进程

使用traces来终止进程

使用多线程模型来终止进程

通过将进程设置为deamon来终止进程

使用隐藏属性_stop()

通过抛出异常来终止进程

# 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()

运行以上程序,一旦raise_exception()被调用,run()函数将被终止。这是因为程序抛出异常,将不在try...finally...函数块中运行,run()函数即被终止。

2.通过一个终止标志来终止进程

# Python program showing

# how to kill threads

# using set/reset stop

# flag

import threading

import time

def run():

while True:

print('thread running

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值