Python threads and global vars
Question: Say I have the following function in a module called "firstModule.py":

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

Now I have a different module called "secondModule.py":

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

I am running a module called "mainModule.py" which has the following (notice
the global "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
    

Basically I want the "addCount" value in both modules to be the one from
"mainModule". After that, when the threads are finished, I want to print the
value of "a" in both of them. The example above doesn't work. I was wondering
how can I fix it.


Answer: Pass 'addCount' to the function 'calculate', return the value of 'a' in
'calculate', and assign it to a new attribute in MyThread instance.

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

