5

你们对以下应用程序使用哪些 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())

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

4

1 回答 1

5

当您创建线程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()
于 2017-03-01T21:18:27.330 回答