python:无法获取线程类实例

2024-09-19 21:02:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个线程,以便同时启动我的类的几个实例。他们应该每x秒写一次度量。。 但目前,指标只写了一次

我尝试改编以下例子: http://www.tutorialspoint.com/python/python_multithreading.htmhttp://python.developpez.com/faq/?page=Thread

class tcSensor(Thread):
    """

    """
    name=""
    label=""
    adapterID=""
    channel=""
    polling_interval=1
    temperature = 0
    ambient = 0
    state =1
    temperatureSensor=object

    def __init__(self,temperatureSensor,name,label,adapterID,channel,polling_interval):
        super(tcSensor, self).__init__()
        self.daemon = True
        self.cancelled = False
        self.temperatureSensor
        self.name = name
        self.label = label
        self.adapterID=adapterID
        self.channel=channel
        self.polling_interval=polling_interval

    def run(self):
        while not self.cancelled:
            self.update()
            sleep(0.1)    

    def cancel(self):
        """End this timer thread"""
        self.cancelled = True

    def update(self):
        print "--update--"
        self.ambient=temperatureSensor.getAmbientTemperature()
        self.temperature=temperatureSensor.getTemperature(self.channel)
        logger.info("%s: ambient=%f sensor=%f" % (self.name,self.ambient,self.temperature))
        pass

# Read config file
Config = ConfigParser.ConfigParser()
Config.read("./thermocouple.config")
i=0
sensor=[]
for section in Config.sections():
    print ("configuring input %s" % section)
    mysensor=(tcSensor(temperatureSensor,section,Config.get(section,"description"),Config.getint(section,"adapterID"),Config.getint(section,"channel"),Config.getfloat(section,"polling_interval")))
    mysensor.daemon= True
    mysensor.start()
    sensor.append(mysensor)

Tags: nameselfconfigdefchannelsectionlabeltemperature
1条回答
网友
1楼 · 发布于 2024-09-19 21:02:47

您正在守护线程,这意味着线程不会阻止解释器退出。在启动线程之后,没有什么要做的了,所以程序终止

尝试在代码底部添加以下内容:

while True:
    sleep(0.1)

您的程序将一直执行,直到您按Ctrl-C。你的线程似乎没有任何清理,但是如果你添加了一些,你可以在try/except中包装这个睡眠循环,然后取消你的线程:

try:
    while True:
        sleep(0.1)
except (KeyboardInterrupt, SystemExit):
    for s in sensor:
        s.cancel()
    for s in sensor:
        s.join()

相关问题 更多 >