python多线程超时检测

自定义装饰器——代码超时检测

# -*- coding: utf-8 -*-
"""
@author:T
@email:ttbjsht@163.com
@File:time_out_decorator
@descr:
@Created on:2023/2/13/09:59
@IDE:PyCharm
"""
import threading
import time

# 错误示例 这个版本的代码 即使被检测代码未超时也会打印代码超时

def watchdog(thread, timeout) -> None:
	'''
	检测装饰器装饰函数对象是否超时
	:param thread: 被检测的对象 被检测对象是个可执行函数使用多线程来执行函数的功能 (如果不使用多线程的话会阻塞无法同时检测运行时间 )
	:param timeout: 定义超时时间
	:return: None
	'''
	time.sleep(timeout)
	if thread.is_alive():  # 如果thread线程 已经执行完毕 则条件成立 执行完毕是线程对象的函数执行完毕 不是线程不存在
		print(f'{thread.name} timeout')
	return


def watchdog_decorator(timeout):
	def decorator(func):
		def wrapper(*args, **kwargs):
			thread = threading.Thread(target=func, args=args, kwargs=kwargs)  # 将被检测的代码创建一个线程
			thread.start()
			watchdog_thread = threading.Thread(target=watchdog, args=(thread, timeout))  # 将检测代码是否超时的函数对象创建一个线程
			watchdog_thread.start()
			# 上面两个线程都是子线程 同时执行
			thread.join()  # 如果watchdog_thread先执行结束也要等 thread执行完毕才能走下面的代码 join是阻塞主线程 执行 thread的,如果没有线程阻塞的话 主线程可能会在thread之前结束掉
			print("主线程运行结束")  #
	
		return wrapper
	
	return decorator

@watchdog_decorator(2)
def test():
	print('test函数开始执行')
	time.sleep(3)
	print('test函数执行结束')


if __name__ == '__main__':
	test()


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值