【发布时间】:2019-06-27 11:56:20
【问题描述】:
我正在使用 Azure IoT Hub、Python 中的 Azure IoT SDK 和一个带有温度和湿度传感器的树莓派做一个遥测应用程序。
湿度 + 温度传感器 => Rasperry Pi => Azure IoT 中心
对于我的应用程序,我使用 2 个循环线程以不同的频率发送数据: - 一个循环收集温度传感器的数据,每 60 秒将其发送到 Azure IoT Hub - 一个循环收集湿度传感器的数据,每 600 秒将其发送到 Azure IoT Hub。
我想正确关闭 2 个循环线程。它们目前正在运行,无法破坏它们。
我使用的是 Python 2.7。 我从 "threading, Thread" 库中听说过 Event,但我找不到一些可以应用的程序结构的好例子。
如何使用 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")
【问题讨论】:
标签: python multithreading python-2.7 python-multithreading