2013-07-17 2 views
1

이 코드를 작성했는데, 리스너 스레드를 생성하여 kill 메시지 서브 프로세스가 작동하지만 testprocess가 실행되지 않는 여러 서브 프로세스가 시작되는 메인 스레드를 갖고 싶다.파이썬 멀티 프로세스 이슈 프로세스가 시작되지 않는다.

from multiprocessing import Process, Pipe 
    from threading import Thread 
    import time 

    Alive = True 

    def listener_thread(conn): #listens for kill from main 
     global Alive 
     while True: 
     data = conn.recv() 
     if data == "kill": 
      Alive = False #value for kill 
      break 

    def subprocess(conn): 
     t = Thread(target=listener_thread, args=(conn,)) 
     count = 0 
     t.start() 
     while Alive: 
       print "Run number = %d" % count 
       count = count + 1 


    def testprocess(conn): 
    t = Thread(target=listner_thread, args=(conn,)) 
    count = 0 
    t.start() 
    while Alive: 
      print "This is a different thread run = %d" % count 
      count = count + 1 

    parent_conn, child_conn = Pipe() 
    p = Process(target=subprocess, args=(child_conn,)) 
    p2 = Process(target=testprocess, args=(child_conn,)) 
    runNum = int(raw_input("Enter a number: ")) 
    p.start() 
    p2.start() 
    time.sleep(runNum) 
    parent_conn.send("kill") #sends kill to listener thread to tell them when to stop 
    p.join() 
    p2.join() 

답변

2

오타가 입력되면 testprocess은 일찍 종료하는 기능을합니다.

listner_threadlistener_thread이어야합니다.

당신이 subprocess 관련 코드를 주석 처리하고 코드를 실행하면 오류 다음이 표시됩니다

Process Process-1: 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap 
    self.run() 
    File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run 
    self._target(*self._args, **self._kwargs) 
    File "t.py", line 25, in testprocess 
    t = Thread(target=listner_thread, args=(conn,)) 
NameError: global name 'listner_thread' is not defined 
+0

오 와우 그것은 바로 내 앞에 있었다. 이제는 둘 다 실행되지만 프로세스가 디버깅 덕분에 무한하게 돌아갑니다! –

+1

@KyleSponable, BTW,'parent_conn.send ("kill")'를 두 번 호출해야합니다. – falsetru

+0

그래서 열린 스레드를 여러 번 호출해야합니다. –

관련 문제