python线程:多个时循环



你们是否对要用于以下应用程序使用的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()
    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()

最新更新