信号量变量如何在python中传递给下面的对象?

时间:2014-06-05 20:52:58

标签: python multithreading scope

在使用这段代码调整几次之后,我在Server对象中删除了sem.release()而没有实际将变量sem传递给它。但它运作得非常好......似乎无法理解为什么错误不会引发未声明的变量/引用

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 个答案:

答案 0 :(得分:1)

在类中访问全局变量没什么特别的。

x = 3

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

xprinter() 

输出:

3

答案 1 :(得分:1)

Server.run中,sem永远不会被声明为本地引用,因此在最终调用Server.run时会在全局范围内查找它。只是在本地范围内定义了名称sem,恰好使用release方法引用了对象。