2013-07-17 88 views
1

我寫了這段代碼,我想有一個主線程啓動多個子進程,產生一個監聽器線程來等待kill消息子進程工作,但testprocess不運行有沒有錯誤任何想法?Python多進程問題進程不啓動

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_thread應該是listener_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,順便說一句,你需要調用'parent_conn.send(「kill」)'兩次。 – falsetru

+0

所以我需要多次打電話給我打開線程? –