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
    评论
您好!对于Python多线程超时问题,有几种常见的解决方案: 1. 使用`threading.Timer`:可以使用`threading.Timer`类来设置线程的超时时间。您可以在启动线程之前创建一个定时器,并在指定时间后触发超时操作。例如: ```python import threading def my_function(): # 线程执行的代码 # 设置超时时间为5秒 timeout = 5 # 创建定时器 timer = threading.Timer(timeout, thread_timeout) # 启动定时器 timer.start() # 启动线程 thread = threading.Thread(target=my_function) thread.start() # 等待线程执行完成 thread.join() # 如果线程在超时时间内未完成,则执行超时操作 if thread.is_alive(): # 执行超时操作 ``` 2. 使用`concurrent.futures`模块:`concurrent.futures`模块提供了一个高级的接口来管理并发任务。您可以使用`ThreadPoolExecutor`类来创建一个线程池,并使用`submit`方法提交任务。可以使用`as_completed`函数来迭代已完成的任务,并设置超时时间。例如: ```python import concurrent.futures def my_function(): # 线程执行的代码 # 设置超时时间为5秒 timeout = 5 # 创建线程池 executor = concurrent.futures.ThreadPoolExecutor() # 提交任务 future = executor.submit(my_function) # 等待任务完成,设置超时时间 try: result = future.result(timeout=timeout) except concurrent.futures.TimeoutError: # 执行超时操作 ``` 这些方法可以帮助您在Python中处理多线程超时问题。根据您的具体需求,可以选择适合您的方法来实现超时控制。希望能对您有所帮助!如果您有任何疑问,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值