【问题标题】:Threading's is_alive method not returning accurate state线程的 is_alive 方法没有返回准确的状态
【发布时间】:2021-04-14 21:22:30
【问题描述】:

我想设置一个监视器,使用一个线程向一组注册的侦听器报告更新。我正在使用threading.Thread。线程应该从第一个侦听器的注册开始,第二个和正在处理的侦听器刚刚添加到侦听器列表中。 我面临 is_alive() 在 start() 方法后不久调用它时返回错误状态的情况。如何检索正确的排队或运行状态?

import threading
import time
from datetime import datetime


class SomeTaskMonitor(threading.Thread):
    __instance = None
    __listenerList = []

    def __new__(cls, *args, **kwargs):
        """
        starts separate thread for monitoring the bus
        """
        if SomeTaskMonitor.__instance is None:
            SomeTaskMonitor.__instance = object.__new__(cls)
        return SomeTaskMonitor.__instance

    def run(self) -> None:
        while True:
            time.sleep(5)
            # normally list of listeners would be checked here for a match and callback initiated
            print("{0} - some event".format(datetime.now()))

    @staticmethod
    def addListener():
        if not SomeTaskMonitor().is_alive():
            SomeTaskMonitor().start()


if __name__ == '__main__':
    # for ease of read not adding listener here but calling class twice
    SomeTaskMonitor().addListener()

    SomeTaskMonitor().addListener()

以上代码产生以下输出(由于第二个侦听器注册,请参阅重复输出):

2021-04-14 23:09:25.818950 - some event
2021-04-14 23:09:25.821855 - some event
2021-04-14 23:09:30.822109 - some event
2021-04-14 23:09:30.823741 - some event

感谢 cmets 或推荐!

【问题讨论】:

    标签: python python-3.x multithreading python-multithreading


    【解决方案1】:

    我仍在寻找上述编码和相关问题的答案,为什么 is_alive() 返回值不能反映排队或启动线程的当前状态。 不过,目前我正在使用以下适合我需要的 WORKAROUND。希望对面临同样问题的其他人有所帮助:

    @staticmethod
    def addListener():
        if len(listenerList) == 0:
            SomeTaskMonitor().start()
    
        listenerList.append(listener)
    
        #if not SomeTaskMonitor().is_alive():
        #    SomeTaskMonitor().start()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 2020-12-19
      相关资源
      最近更新 更多