首页 > 解决方案 > 控制线程的正确方法是什么?

问题描述

我大约需要运行 3 或 5 个线程,这些线程监视操作系统中的一些活动。因此,主程序必须在后台运行。我已经阅读了很多示例和解释,但我还不清楚如何在后台启动线程和主程序,然后如何控制它们。

我从主程序以守护程序模式启动线程:

import threading
import time

def fun1():
    while True:
        print("Thread 1")
        time.sleep(1)

def fun2():
    while True:
        print("Thread 2")
        time.sleep(1)

def fun3():
    while True:
        print("Thread 3")
        time.sleep(1)

def main():
    thread1 = threading.Thread(target=fun1)
    thread1.daemon = True
    thread1.start()

    thread2 = threading.Thread(target=fun2)
    thread2.daemon = True
    thread2.start()

    thread3 = threading.Thread(target=fun3)
    thread3.daemon = True
    thread3.start()

if __name__ == '__main__':
    try:
        main()
        while True:
            print("------------")
            print("Main program")
            print("------------")
            time.sleep(3)
    except (KeyboardInterrupt, SystemExit):
        print("Terminated")

然后我main在后台运行程序(我不确定这是实现我想要实现的最佳方法):

python daemon_thread.py &

如果我需要停止特定线程、更改其状态或其他什么,如何在主程序初始化后控制线程?如何访问特定线程或主程序?

标签: pythonmultithreadingthread-safety

解决方案


我现在明白了如何解决问题:我有一个在后台运行的主程序,这个主程序有一些线程。但是我想用另一个脚本或程序安全地停止带有线程的主程序,并且在某些情况下暂停和恢复线程。

我对如何使用线程没有正确的概念。我可以使用数据库或配置文件从主程序 How? 停止或向该线程发送信号。

我用这些更改更新了我的项目:

import threading
import time
import sqlite3

def fun1(stop_event1):
    while not stop_event1.is_set(): 
        print("Thread 1")
        time.sleep(1)

def fun2(stop_event2):
    while not stop_event2.is_set(): 
        print("Thread 2")
        time.sleep(1)

def fun3(stop_event3):
    while not stop_event3.is_set(): 
        print("Thread 3")
        time.sleep(1)

def main():
    stop_event1 = threading.Event()
    thread1 = threading.Thread(target=fun1, args=(stop_event1,))
    thread1.daemon = True
    thread1.start()

    stop_event2 = threading.Event()
    thread2 = threading.Thread(target=fun2, args=(stop_event2,))
    thread2.daemon = True
    thread2.start()

    stop_event3 = threading.Event()
    thread3 = threading.Thread(target=fun3, args=(stop_event3,))
    thread3.daemon = True
    thread3.start()

    while True:
        print("------------")
        print("Main program")
        print("------------")
        time.sleep(3)            
        if alive_main():
            print("Finish Threads")
            stop_event1.set()
            stop_event2.set()
            stop_event3.set()

            print("Bye")
            break


def alive_main():
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    c.execute('SELECT alive_main FROM config')
    row = c.fetchone()
    if row[0] == 1:
        return True
    else:
        return False

if __name__ == '__main__':
    try:
        main()
    except (KeyboardInterrupt, SystemExit):
        print("Terminated")

如果我想用另一个类或脚本更改我的线程的状态,我只需更改我的数据库中的配置表,这将在主函数中的线程中生效。在这个例子中,如果我正确地停止我的线程和程序,我只更新表,就是这样。

sqlite> UPDATE config SET alive_main = 1;

我需要阅读有关信号条件对象的信息以正确补充线程的使用。

感谢大家!


推荐阅读