0

I need run 3 or 5 threads approx, this threads monitoring some activities in the OS. Because of this, the main program must be running in background. I've read many examples and explanations, but I'm not clear yet how to launch threads and main program in the background and after that, how to control them.

I start threads in daemon mode from main program:

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

and after that I run the main program in background with (I'm not sure that this is the best way to do it for what I want to achieve):

python daemon_thread.py &

How control the threads after main program initialization if I need stop a specific thread, change its state, or whatever? How to access a specific thread or the main program?

martineau
  • 119,623
  • 25
  • 170
  • 301
DrakoRod
  • 31
  • 8
  • 2
    you "access" it like any other python object ... if you want a better answer we will need a more realistic example of what you want to do when you "access" it – Joran Beasley Oct 10 '18 at 23:08
  • You need to be very specific about what ways you want to "control" them (the threads). How that needs to be done will likely depend on those details. – martineau Oct 10 '18 at 23:28
  • There is no `kill` method for threads. If you want to kill a thread, you should have that thread check a variable occasionally. For example, instead of `while True:`, use something like `while thread_1_keep_running:`, where `thread_1_keep_running` is a variable that you set to `True` or `False`. – John Anderson Oct 10 '18 at 23:34
  • Read about [Condition Objects](https://docs.python.org/3/library/threading.html#condition-objects) – stovfl Oct 11 '18 at 06:47
  • @JoranBeasleyI refer to "access" how I can in some time stop just the Thread 1 and change time sleep in Thread 2, and change a variable to Thread 3. But I don't understan how do that because the main program run in background in OS. – DrakoRod Oct 11 '18 at 14:49
  • actually, I read about how to safely stop Thread https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python, but if my script with the main program start in background on OS, how I can send signals or access to this script or class if I make a class instead script?? – DrakoRod Oct 11 '18 at 14:54
  • @martineau I refer to control them, how to a stop someone, change variable, change sleep time if the main program is in background? How to send with other script a signal to specific thread?? – DrakoRod Oct 11 '18 at 15:12
  • @stovfl Thanks! I will read about that. – DrakoRod Oct 11 '18 at 15:21
  • *I refer to control them ...*, read [Section: Signals and threads](https://docs.python.org/3/library/signal.html#module-signal). – stovfl Oct 11 '18 at 15:54
  • "..., and after that, how to control them." Don't think about it in terms of _controlling_ threads. Think about how the threads can _cooperate_ with each other to achieve some common purpose. – Solomon Slow Oct 11 '18 at 16:41
  • DrakoRod: You can't actually stop and then restart threads, but you can make them pause and optionally resume. See my answer to the question [How to start and stop thread?](https://stackoverflow.com/questions/15729498/how-to-start-and-stop-thread) – martineau Oct 11 '18 at 17:21

1 Answers1

0

I understand now how to do, to resume the problem: I have a main program running in background and this main program have some threads. But I want with another script or program stop the main program with the threads safetly and in some cases pause and resume threads.

I didn't have a correctly concept about how to use the Threads. I can stop or send signal to this threads from main program How?,with a database or config file.

I updated my project with this changes:

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

If I want change with another class or script the state of my threads, I just change config table in my database y this take effect in the Threads, from main function. In this example if I stop correctly my threads and program just I update table, that's it.

sqlite> UPDATE config SET alive_main = 1;

I need read about Signals and Condition Objects to complement correctly Threads uses.

Thanks everyone!

DrakoRod
  • 31
  • 8