• WithThread多线程识别某一线程受阻


    从源代码修改

    1. from threading import Thread
    2. from queue import Queue
    3. class WithThread:
    4. def __init__(self, thread_num):
    5. self.thread_num = thread_num
    6. self.task_queue = Queue()
    7. self.threads = []
    8. self.is_running = False
    9. self.thread_status = [True] * thread_num # 新增一个列表记录每个线程的状态
    10. def put(self, func, args=()):
    11. if not self.is_running:
    12. self.start()
    13. self.task_queue.put((func, args))
    14. def start(self):
    15. self.is_running = True
    16. for i in range(self.thread_num):
    17. t = Thread(target=self._run, args=(i,)) # 将线程ID作为参数传入方法中
    18. t.start()
    19. self.threads.append(t)
    20. def stop(self):
    21. self.is_running = False
    22. for t in self.threads:
    23. t.join()
    24. def _run(self, i):
    25. while self.is_running:
    26. try:
    27. func, args = self.task_queue.get(timeout=1)
    28. except Exception as e:
    29. # 捕获Empty异常
    30. continue
    31. try:
    32. func(*args)
    33. except Exception as e:
    34. print("任务执行失败: ", e)
    35. finally:
    36. self.task_queue.task_done()
    37. self.thread_status[i] = True # 在任务完成后将状态标记为True
    38. def get_thread_status(self):
    39. return self.thread_status # 返回线程状态列表

    新增了一个thread_status列表来记录每个线程的状态,并在每个线程的_run方法中更新状态。另外,我们还新增了一个get_thread_status方法,用于获取所有线程的状态。

    1. from threading import Thread
    2. from queue import Queue
    3. class WithThread:
    4. def __init__(self, thread_num, max_queue_size=100):
    5. self.thread_num = thread_num
    6. self.task_queue = Queue()
    7. self.max_queue_size = max_queue_size
    8. self.threads = []
    9. self.is_running = False
    10. def put(self, func, args=()):
    11. if not self.is_running:
    12. self.start()
    13. self.task_queue.put((func, args))
    14. def start(self):
    15. self.is_running = True
    16. for i in range(self.thread_num):
    17. t = Thread(target=self._run)
    18. t.start()
    19. self.threads.append(t)
    20. def stop(self):
    21. self.is_running = False
    22. for t in self.threads:
    23. t.join()
    24. def _run(self):
    25. while self.is_running:
    26. try:
    27. func, args = self.task_queue.get(timeout=1)
    28. except Exception as e:
    29. # 捕获Empty异常
    30. continue
    31. try:
    32. func(*args)
    33. except Exception as e:
    34. print("任务执行失败: ", e)
    35. finally:
    36. self.task_queue.task_done()
    37. # 判断队列长度是否超出阈值
    38. if self.task_queue.qsize() > self.max_queue_size:
    39. print("当前线程受阻,队列长度:", self.task_queue.qsize())

    新增了一个max_queue_size参数,并在线程的_run方法中判断队列长度是否超过该阈值。如果队列长度超过阈值,就认为该线程受阻。

  • 相关阅读:
    nacos配置中心及服务注册中心使用
    golang容易导致内存泄漏的几种情况
    第二十章·中介者模式
    基于SSM线上课程管理系统设计与实现
    MSSQL-逻辑级常用命令
    【Linux·克莱因计划】实用指令操作汇总合集(上)
    GoLang读写数据---上
    bat脚本基础
    蜂窝移动终端的Cat指的是什么?
    什么是MDM
  • 原文地址:https://blog.csdn.net/EaSoNgo111/article/details/133929931