2017-02-28 3 views
2

다음 응용 프로그램에 사용할 파이썬 모듈에 대한 권장 사항이 있습니다. 두 스레드 (모두 while True: 루프)를 실행하는 데몬을 만들고 싶습니다.Python Threading : True While 루프 여러 번

예를 들어 주시면 감사하겠습니다. 미리 감사드립니다.

업데이트 : 여기는 내가 생각해 낸 것이지만, 예상 한 동작이 아닙니다.

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'이 좋습니다. 'while true'.... 실행되는 코드는 차단되는 경향이 있거나 CPU 집약적입니까? 하위 프로세스가 필요할 수 있습니다. – tdelaney

+0

스레드가 지속적이면'ThreadPool'은 좋지 않습니다. '풀 (pool) '은 일반적으로 말하는 개별 작업을위한 것입니다 ... – 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()