0

我知道在这种情况下,全局变量并不总是处理事情的最佳方式,它们对我正在做的事情很好。我不会做繁重的读/写,主要是读。

    alive = {'subAlive': True, 'testAlive': True};

    def sub_listener(conn): #listens for kill from main 
        global alive
        while True:
        data = conn.recv()
        if data == "kill":
           alive['subAlive'] = False; #value for kill 
           break

     def subprocess(conn, threadNum):
         t = Thread(target=sub_listener, args=(conn,))
         count = 0                
         threadVal = threadNum 
         t.start()
         run = alive[subAlive];
         while run:
               print "Thread %d Run number = %d" % (threadVal, count)
               count = count + 1

       sub_parent, sub_child = Pipe()
       runNum = int(raw_input("Enter a number: ")) 
       threadNum = int(raw_input("Enter number of threads: "))

       print "Starting threads"

       for i in range(threadNum):
           p = Process(target=subprocess, args=(sub_child, i))
           p.start()

       print "Starting run"

       time.sleep(runNum) 

       print "Terminating Subprocess run"
       for i in range(threadNum):
           sub_parent.send("kill") #sends kill to listener

       p.join()

我收到这个错误

 NameError: global name 'testAlive' is not defined
 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 "multiprocessDemo.py", line 38, in subprocess
   run = alive[subAlive];
 NameError: global name 'subAlive' is not defined

我尝试了几种不同的方式访问字典,但我似乎无法在谷歌上找出问题所在。如果我使用单独的变量,它确实有效,但不会很好地动态扩展。

4

1 回答 1

3

在周围加上引号subAlive

run = alive['subAlive']
于 2013-07-18T01:02:39.670 回答