2

After tweaking with this piece of code a few times, I dropped sem.release() in the Server object WITHOUT actually passing the variable sem into it. But it works wonderfully... Can't seem to understand why a error wasn't throw for undeclared variable/reference

import threading,time

class Server(threading.Thread):

  def __init__(self, hostname):
    super(Server, self).__init__()
    self.__hostname = hostname

  def run(self):
    print self.__hostname+' left'
    time.sleep(5)
    print self.__hostname+' back'
    sem.release()

#init
sem = threading.BoundedSemaphore(2)
for x in xrange(1,8):
  sem.acquire()
  Server('thread '+str(x)).start()
2
  • not really an answer but I think it is common to acquire the semaphore in start or run rather than in the main thread ... Commented Jun 5, 2014 at 21:51
  • I understand it now... thanks everyone! I didn't know variables declared outside of a class is still a global variable Commented Jun 18, 2014 at 16:09

2 Answers 2

1

There's nothing special about accessing a global variable inside a class.

x = 3

class xprinter(object):
    def __init__(self):
        print(x)

xprinter() 

output:

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

Comments

1

In Server.run, sem is never declared as a local reference, so it is looked up in the global scope when Server.run is eventually called. It just so happens that you have a name sem defined in the local scope that happens to reference an object with a release method.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.