-1

A couple of questions on this, but I believe I'm already following their solutions. In the following example, can anyone say why the thread doesn't find that boolean is updated to True? I've defined it globally..

import threading
import time

boolean = False

class ThreadClass(threading.Thread):
  def __init__(self):
    global boolean
    super(ThreadClass, self).__init__()
  def run(self):
    global boolean
    for i in range(6):
      print str(i)
      time.sleep(1)

t = ThreadClass().start()
time.sleep(3)
boolean = True
print 'end script'
0
1
2
end script
3
4
5
geotheory
  • 22,624
  • 29
  • 119
  • 196
  • 1
    You are not looking at boolean in the thread... so how do you know it's not seeing it? – John Szakmeister Dec 01 '15 at 10:59
  • @jszakmeister, Beat me to it. That question takes the cake. It's equivalent to asking why `x = 10` and `print 'hello'` doesn't print 10. – 7stud Dec 01 '15 at 10:59
  • Fair criticism. I have a different script that did look at the global, but I toyed it for the question without a sanity check.. – geotheory Dec 01 '15 at 11:32

1 Answers1

2

Change print str(i) to print str(i), boolean and you'll see that it does change:

:: python so-python-thread.py
0 False
1 False
2 False
end script
3 True
4 True
5 True

Here's my version of the code:

import threading
import time


boolean = False


class ThreadClass(threading.Thread):
    def __init__(self):
        super(ThreadClass, self).__init__()

    def run(self):
        global boolean
        for i in range(6):
            print str(i), boolean
            time.sleep(1)


t = ThreadClass().start()
time.sleep(3)
boolean = True
print 'end script'

You actually have a small bug:

t = ThreadClass().start()

The start() method returns None, so t will be None. You need to separately instantiate the thread, then start it. Also, I'd explicitly wait for the thread to join:

import threading
import time


boolean = False


class ThreadClass(threading.Thread):
    def __init__(self):
        super(ThreadClass, self).__init__()

    def run(self):
        global boolean
        for i in range(6):
            print str(i), boolean
            time.sleep(1)


t = ThreadClass()
t.start()

time.sleep(3)
boolean = True

t.join()
print 'end script'
John Szakmeister
  • 44,691
  • 9
  • 89
  • 79