python - 如何正确结束 2 循环线程?
问题描述
我正在使用 Azure IoT Hub、Python 中的 Azure IoT SDK 和一个带有温度和湿度传感器的树莓派做一个遥测应用程序。
湿度 + 温度传感器 => Rasperry Pi => Azure IoT Hub
对于我的应用程序,我使用 2 个循环线程以不同频率发送数据: - 一个循环收集温度传感器的数据,每 60 秒将其发送到 Azure IoT Hub - 一个循环收集湿度传感器的数据并将其发送到Azure IoT 中心每 600 秒。
我想正确关闭 2 个循环线程。他们目前正在运行,无法打破它们。
我正在使用 Python 2.7。我从“线程,线程”库中听说过事件,但我找不到一些可以应用的程序结构的好例子。
如何使用 Event 正确关闭线程?如何用另一种方法结束这些循环?
这是我使用 2 个线程(包括循环)的代码结构。
from threading import Thread
def send_to_azure_temperature_thread_func:
client = iothub_client_init()
while True:
collect_temperature_data()
send_temperature_data(client)
time.sleep(60)
def send_to_humidity_thread_func():
client = iothub_client_init()
while True:
collect_humidity_data()
send_humidity_data(client)
time.sleep(600)
if __name__ == '__main__':
print("Threads...")
temperature_thread = Thread(target=send_to_azure_temperature_thread_func)
temperature_thread.daemon = True
print("Thread1 init")
humidity_thread = Thread(target=send_to_azure_humidity_thread_func)
humidity_thread.daemon = True
print("Thread2 init")
temperature_thread.start()
humidity_thread.start()
print("Threads start")
temperature_thread.join()
humidity_thread.join()
print("Threads wait")
解决方案
Event
似乎是一个好方法。创建一个并将其传递给所有线程并替换sleep()
byEvent.wait()
并检查是否需要保留循环。
在主线程中,可以将事件设置为向线程发出信号,表明它们应该离开循环并因此结束它们自己。
from threading import Event, Thread
def temperature_loop(stop_requested):
client = iothub_client_init()
while True:
collect_temperature_data()
send_temperature_data(client)
if stop_requested.wait(60):
break
def humidity_loop(stop_requested):
client = iothub_client_init()
while True:
collect_humidity_data()
send_humidity_data(client)
if stop_requested.wait(600):
break
def main():
stop_requested = Event()
print('Threads...')
temperature_thread = Thread(target=temperature_loop, args=[stop_requested])
temperature_thread.daemon = True
print('Thread1 init')
humidity_thread = Thread(target=humidity_loop, args=[stop_requested])
humidity_thread.daemon = True
print('Thread2 init')
temperature_thread.start()
humidity_thread.start()
print('Threads start')
time.sleep(2000)
stop_requested.set()
temperature_thread.join()
humidity_thread.join()
print('Threads wait')
if __name__ == '__main__':
main()
推荐阅读
- python - 打印仅显示来自 json 的最后一个寄存器
- sql-server - 查询 SQL 数据库并为每条记录发送电子邮件 - PowerShell
- sql - where 子句中的用例语句别名
- adb - 来自 Docker 容器的 ADB 通过 wifi
- d3.js - 可折叠径向树 D3.js v5
- c++ - 指向浮点指针的 int 指针 - reinterpret_cast
- angular - 如何使用可观察对象的可观察对象顺序发送 GET 请求
- verilog - Verilog综合给了我一个我不明白的错误
- java - 调用 EditText 的 onClick 事件,当单击它所在的布局内部时
- router - 在 Apple M1 上构建 OpenWRT 包而不选择 ARM