如何解决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
如您所见,我必须打印一次已关闭,但它出现了两次
致谢
解决方法
我发现是烧瓶螺纹融合了螺纹的顶盖,所以我将其卸下,然后一切正常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。