0

Consider the following code:

from threading import Thread 

def main():
    number = 5

    class my_thread(Thread):
        def __init__(self, range):
            Thread.__init__(self)
            self.range = range

        def run(self):
            global number
            for i in self.range:
                number += 1

    t1 = my_thread(range(4))
    t1.start()
    t1.join()
    print number

main()

The output from this program is

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Tools\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Dev\Workspace\Hello World\Hello.py", line 14, in run
    number += 1
NameError: global name 'number' is not defined

5

Evidently, my_thread does not have access to number. Why is this, and how can I access it correctly?

1 Answer 1

2

You need to make number a global at its first definition, like this:

def main():
    global number
    number = 5

...etc...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.