Python Threading: Multiple While True loops

dobbs picture dobbs · Feb 28, 2017 · Viewed 10.9k times · Source

Do you guys have any recommendations on what python modules to use for the following application: I would like to create a daemon which runs 2 threads, both with while True: loops.

Any examples would be greatly appreciated! Thanks in advance.

Update: Here is what I have come up with, but the behavior is not what I expected.

import time
import threading

class AddDaemon(object):
    def __init__(self):
        self.stuff = 'hi there this is AddDaemon'

    def add(self):
        while True:
            print self.stuff
            time.sleep(5)


class RemoveDaemon(object):
    def __init__(self):
        self.stuff = 'hi this is RemoveDaemon'

    def rem(self):
        while True:
            print self.stuff
            time.sleep(1)

def run():
    a = AddDaemon()
    r = RemoveDaemon()
    t1 = threading.Thread(target=r.rem())
    t2 = threading.Thread(target=a.add())
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    while True:
        pass

run()

output

Connected to pydev debugger (build 163.10154.50)
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon

It looks like when I try to create a thread object using:

t1 = threading.Thread(target=r.rem())
t2 = threading.Thread(target=a.add())

the while loop in r.rem() is the only one that gets executed. What am I doing wrong?

Answer

Aaron picture Aaron · Mar 1, 2017

When you are creating your threads t1 and t2, you need to pass the function not call it. when you call r.rem(), it enters the infinite loop before you create the thread and separate it from the main one. the solution to this is to remove the parenthesis from r.rem() and a.add() in your thread constructors.

import time
import threading

class AddDaemon(object):
    def __init__(self):
        self.stuff = 'hi there this is AddDaemon'

    def add(self):
        while True:
            print(self.stuff)
            time.sleep(3)


class RemoveDaemon(object):
    def __init__(self):
        self.stuff = 'hi this is RemoveDaemon'

    def rem(self):
        while True:
            print(self.stuff)
            time.sleep(1)

def main():
    a = AddDaemon()
    r = RemoveDaemon()
    t1 = threading.Thread(target=r.rem)
    t2 = threading.Thread(target=a.add)
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    time.sleep(10)

if __name__ == '__main__':
    main()