Kyle Sponable
Kyle Sponable

Reputation: 735

cant reference a global dictionary entry

I am aware that global variables are not always the best way to deal with things in this case they are fine for what I am doing. I am not going to be doing heavy read/writes mostly just reads.

    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()

I get this error

 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

I have tried accessing the dictionary a few different ways and I can't seem to find out what is wrong on google. If I use separate variables it does work but that wont dynamically scale well.

Upvotes: 0

Views: 93

Answers (1)

tamasgal
tamasgal

Reputation: 26329

Put quotes around subAlive:

run = alive['subAlive']

Upvotes: 3

Related Questions