1

我写了这段代码,我想要一个主线程来启动多个子进程,这些子进程产生一个侦听器线程以等待终止消息子进程工作但 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()
4

1 回答 1

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
于 2013-07-17T04:41:07.983 回答