views:

71

answers:

2

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.

+1  A: 

Modules in python are singletons, so you can put your global variables in module globalModule.py and have both firstModule, secondModule, and mainModule import globalModule and they will all access the same addCount.

However, in general it's a bad practice for threads to have a global state.

This will never work:

print firstModule.a print secondModule.a

because in here:

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

a is a local variable to the function calculate.

If you really want to write a as a module-level variable, add global declaration:

def calculate():
   # addCount value here should be used from the mainModule
   global a
   a=random.randint(0,5) + addCount
Lie Ryan
OK it's working now but I can't set the global variables..
Gavriel
+2  A: 

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
suzanshakya