2013-07-11 178 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()