2010-10-09 116 views
0

说我有一个名为“firstModule.py”模块中的如下功能:的Python线程和全局变量

def calculate(): 
    # addCount value here should be used from the mainModule 
    a=random.randint(0,5) + addCount 

现在我有一个名为“secondModule.py”不同的模块:

def calculate(): 
    # addCount value here too should be used from the mainModule 
    a=random.randint(10,20) + addCount 

我运行一个名为 “mainModule.py” 模块,该模块具有以下(注意全球 “addCount” VAR):

import firstModule 
import secondModule 

addCount=0 

Class MyThread(Thread): 
    def __init__(self,name): 
     Thread.__init__(self) 
     self.name=name 

    def run(self): 
     global addCount 
     if self.name=="firstModule": 
     firstModule.calculate() 
     if self.name=="secondModule": 
     secondModule.calculate() 

def main(): 
    the1=MyThread("firstModule"); 
    the2=MyThread("secondModule"); 
    the1.start() 
    the2.start() 
    the1.join() 
    the2.join() 

    # This part doesn't work: 
    print firstModule.a 
    print secondModule.a 

BASICA我希望两个模块中的“addCount”值是“mainModule”中的值。之后,线程完成后,我想在它们两个中打印“a”的值 。上面的例子不起作用。我想知道如何解决这个问题。

回答

2

python中的模块是单例,所以你可以把你的全局变量放在模块globalModule.py中,同时具有firstModule,secondModule和mainModule import globalModule,它们都将访问相同的addCount。

但是,一般来说,线程拥有全局状态是一种不好的做法。

这不会有任何效果:

打印firstModule.a 打印secondModule.a

因为在这里:

def calculate(): 
    # addCount value here should be used from the mainModule 
    a=random.randint(0,5) + addCount 

a是一个局部变量的函数calculate

如果你真的想写a作为一个模块级变量,添加全局声明:

def calculate(): 
    # addCount value here should be used from the mainModule 
    global a 
    a=random.randint(0,5) + addCount 
+0

确定它正在工作,但我无法设置全局变量.. – Gavriel 2010-10-09 17:12:07

4

通行证“addCount”的功能“计算”,返回“A”的价值“计算',并将其分配给MyThread实例中的新属性。

def calculate(addCount): 
    a = random.randint(0, 5) + addCount 
    return a