简体   繁体   中英

Python threads and global vars

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM