【问题标题】:What is the correct way to control threads?控制线程的正确方法是什么?
【发布时间】:2018-10-10 23:02:24
【问题描述】:

我需要运行大约 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 &

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

【问题讨论】:

  • 你像任何其他 python 对象一样“访问”它......如果你想要一个更好的答案,我们需要一个更真实的例子来说明你在“访问”它时想要做什么
  • 您需要非常具体地了解您想要“控制”它们(线程)的方式。需要如何完成可能取决于这些细节。
  • 线程没有kill 方法。如果你想杀死一个线程,你应该让那个线程偶尔检查一个变量。例如,不要使用while True:,而是使用while thread_1_keep_running: 之类的东西,其中thread_1_keep_running 是您设置为True 或False 的变量。
  • @JoranBeasley我指的是“访问”我如何在某些时候停止线程 1 并更改线程 2 中的时间睡眠,并将变量更改为线程 3。但我不明白怎么做那是因为主程序在操作系统的后台运行。

标签: python multithreading thread-safety


【解决方案1】:

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

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

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

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;

我需要阅读Signals 和Condition Objects 以正确补充线程的使用。

谢谢大家!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2010-10-10
    相关资源
    最近更新 更多