如何正确结束2循环线程?

2024-04-19 00:38:30 发布

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

我正在使用azureiot Hub、Python中的azureiot SDK和带有温度和湿度传感器的raspberry pi做一个遥测应用程序。你知道吗

湿度+温度传感器=>;Rasperry Pi=>;Azure物联网中心

对于我的应用程序,我使用2个循环线程以不同的频率发送数据: -一个环路收集温度传感器的数据,并每60秒将其发送到Azure IoT Hub -一个环路收集湿度传感器的数据,并每600秒将其发送到Azure IoT Hub。你知道吗

我想正确关闭2个循环线程。他们目前没有办法打破他们。你知道吗

我使用的是python2.7。 我从“线程,线程”库中听说了这个事件,但是我找不到一些好的程序结构示例来应用。你知道吗

如何使用事件正确关闭线程?如何用另一种方法结束这些循环?你知道吗

下面是我的代码结构,使用了包括循环在内的两个线程。你知道吗

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")

Tags: toclientsendtruedatainitazure线程
1条回答
网友
1楼 · 发布于 2024-04-19 00:38:30

Event似乎是个不错的方法。创建一个并将其传递给所有线程,用Event.wait()替换sleep(),并检查是否需要保留循环。你知道吗

在主线程中,可以将事件设置为向线程发出信号,表示它们应该离开循环,从而结束自己。你知道吗

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()

相关问题 更多 >