2013-07-11 182 views
-1

我有多个类(运行同时使用线程)。他们都需要访问一个词典/物件(从数据库中包含的配置值,并提及的所有其他物体,能够调用2个线程之间的方法)共享数据

什么是实现这一目标的最佳方式是什么?
我应该创建一个模块来保存并获取数据吗?
全局变量?

我是很新,Python和我觉得像IM接近这个错误的方式

编辑(小例子脚本)

#!/usr/local/bin/python3.3 

class foo(threading.Thread): 
    def run(self): 
     # access config from here 
     y = bar(name='test').start() 

     while True: 
      pass 
    def test(self): 
     print('hello world') 

class bar(threading.Thread): 
    def run(self): 
     # access config from here 
     # access x.test() from here 

if __name__ == '__main__': 
    x = foo(name='Main').start() 
+1

你能成为一个更具体一点?这取决于你想要实现什么。 –

+0

@JoelCornett我已经添加了一个小例子。 – peipst9lker

+0

我仍然不确定你想要完成什么,但在我看来,当你实例化它时,你可以将'test'方法传递给'y'。当然,你必须修改继承的构造函数bar.__ init __()'来接受和存储参数。 –

回答

1

如果你的程序是足够大的,有很多的全球数据,创建一个模块并将所有全局数据放在那里是一个好主意。从其他模块导入此模块并使用它。如果程序很小,那么也许全局变量更合适。我在这里假设这将是一个只读结构,否则事情会变得复杂。下面是第一种情况为例(假设Config在文件global_mod.py类):

from global_mod import Config 

class foo(threading.Thread): 
    def run(self): 
     # do something with cfg 
     y = bar(name='test').start() 

     while True: 
      pass 

    def test(self): 
     print('hello world') 

class bar(threading.Thread): 
    def run(self): 
     # do something with cfg 
     # access x.test() from here 

if __name__ == '__main__': 
    cfg = Config() 
    x = foo(name='Main').start()