Python-线程复制重复

问题描述

正在尝试在我的python应用程序中执行多线程。我得到了创建子线程的主线程。但是,对于测试,仅使用1个线程。线程必须执行的任务是收集数据,然后将其存储在DB中。但是,我看到它存储了两次,调试后发现我得到了2个线程而不是1个线程。

主程序:


app = webApp.app

def main_program():
    sleep(3)
    while True:
        Sensor.sensors.items()


def start_webApp():
    bottle.run(app=app,host='0.0.0.0',port=8080,reloader=True,debug=True)


if __name__ == '__main__':
    app_thread = threading.Thread(target=start_webApp).start()
    s1_thread = threading.Thread(target=sensor_thread.start_sensor_reading,args=(14,SL.bedroom_1,),name="Sensor_1")
    s1_thread.start()
    main_program()

线程文件

def start_sensor_reading(sensor_pin,sensor_location):
    sleep(3)
    global sensor,current,pulses,sensor_status
    sensor = DigitalInputDevice(sensor_pin)
    current = WFS.isIdle
    pulses = 0
    valve_open_time = 0
    valve_close_time = 0
    Sensor.sensors[sensor_location] = False
    doc_ref = db.collection(sensor_location.value).document()
    while True:
        if current == WFS.isIdle:
            print("idle")
        if sensor.value == 1:
            print("S IS OPENED")
            current = WFS.isOpened
            if pulses == 0:
                valve_open_time = datetime.datetime.Now()
        if current == WFS.isOpened:
            m,s = get_time_diff(valve_open_time)
            if s > 30:
                Sensor.sensors[sensor_location] = True
            while sensor.value == 1:
                print("S IS OPENED - Counting pulses")
                pulses += sensor.value
            current = WFS.isNoisy
        if current == WFS.isNoisy:
            print("S IN NOISE")
            valve_close_time = datetime.datetime.Now()
            while sensor.value == 0:
                print("S IN NOISE - checking if will close")
                minutes,seconds = get_time_diff(valve_close_time)
                if seconds > 3:
                    current = WFS.isClosed
                    break
        if current == WFS.isClosed:
            current = WFS.isIdle
            sleep(10) <<< HERE IS THE PROBLEM - I do sleep 10 secs to see how many times it prints <<<<<<
            print("S IS CLOSED - SAVING IN DB - SENSOR PIN : " + str(sensor_pin))
            sleep(10)
            m,s = get_time_diff(valve_open_time)
            duration = str(m) + ":" + str(s)
            liters = pulses / 450
            doc_ref.set({
                'Liters': liters,'Started_At': valve_open_time,'Stopped_At': valve_close_time,'Duration': duration
            })
            pulses = 0

控制台输出

S IN NOISE - checking if will close
S IN NOISE - checking if will close
S IS CLOSED - SAVING IN DB - SENSOR PIN : 14
S IS CLOSED - SAVING IN DB - SENSOR PIN : 14
idle
idle
idle
idle

如您所见,我必须打印一次关闭,但它出现了两次

致谢

解决方法

我发现是烧瓶螺纹融合了螺纹的顶盖,所以我将其卸下,然后一切正常。