2010-10-09 128 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