2017-02-28 170 views
2

你们对于以下应用程序使用什么python模块有任何建议:我想创建一个运行2个线程的守护进程,这两个线程都使用while True:循环。Python Threading:Multiple 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循环是被执行的唯一一个。我究竟做错了什么?

+0

很多选项......但multiprocessing.Pool.ThreadPool是一个很好的选择。那'虽然真实'....它会运行的代码倾向于阻止还是cpu密集?子进程可能是需要的。 – tdelaney

+0

如果线程持久化,'ThreadPool'不是一个好主意; '池'是专为离散任务,一般来说... – ShadowRanger

+1

我刚刚几个星期前这样做。类似的事情。我使用'concurrent.futures'和'supervisord'作为守护进程工具。但是你也可以使用'pm2'。我正在构建一个聊天机器人并使用多个线程处理大型流。 –

回答

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