Python 线程化:多个 While True 循环

Python Threading: Multiple While True loops

你们对以下应用程序使用什么 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 循环是唯一被执行的循环。我做错了什么?

当您创建线程 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()
    <b>t1 = threading.Thread(target=r.rem)
    t2 = threading.Thread(target=a.add)</b>
    t1.setDaemon(True)
    t2.setDaemon(True)
    t1.start()
    t2.start()
    time.sleep(10)

if __name__ == '__main__':
    main()