2017-09-05 143 views
0

我寫了一些代碼,我有線程,並且一次使用各種不同的函數。我有一個名爲ref的變量,每個線程都有所不同。函數之間但不是線程的Python共享變量

ref是在線程函數內的函數中定義的,所以當我使用全局線程ref時,所有線程對於ref(我不想要)使用相同的值。但是,當我不使用全局ref時,其他函數不能使用ref,因爲它沒有被定義。

例如爲:

def threadedfunction(): 
    def getref(): 
     ref = [get some value of ref] 
    getref() 
    def useref(): 
     print(ref) 
    useref() 
threadedfunction() 
+0

您是否聽說過參數和返回值?您應該使用這些來傳遞數據進出功能。 – user2357112

+1

這是你甚至在考慮做多線程任何事情之前需要100%滿意的東西。 – user2357112

+0

如果您在線程之間編寫代碼,則還需要使用線程安全類型。 Python的內置類型不保證是安全的。 –

回答

0

如果定義refglobal不適合你的需求,那麼你沒有太多其他選擇......

編輯你的函數的參數和返回。可能的解決方案:

def threadedfunction(): 

    def getref(): 
     ref = "Hello, World!" 
     return ref # Return the value of ref, so the rest of the world can know it 

    def useref(ref): 
     print(ref) # Print the parameter ref, whatever it is. 

    ref = getref() # Put in variable ref whatever function getref() returns 
    useref(ref) # Call function useref() with ref's value as parameter 

threadedfunction() 
+0

非常感謝 –