Python线程:多个True循环

时间:2017-02-28 02:51:02

标签: python multithreading daemon python-daemon

你们对于下面的应用程序使用什么python模块有什么建议:我想创建一个运行2个线程的守护进程,都有while True:个循环。

任何例子都将非常感谢!提前谢谢。

更新: 这是我想出的,但行为不是我的预期。

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

输出

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

当我尝试使用:

创建线程对象时
t1 = threading.Thread(target=r.rem())
t2 = threading.Thread(target=a.add())

r.rem()中的while循环是唯一被执行的循环。我做错了什么?

1 个答案:

答案 0 :(得分:1)

创建线程t1t2时,需要传递函数而不是调用它。当你调用r.rem()时,它会在你创建线程并将其与主线程分开之前进入无限循环。解决方法是从线程构造函数中的r.rem()a.add()中删除括号。

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