2016-10-24 34 views
1

爲什麼my_string的值不會更改?Python:從另一個線程更改變量值

我從兩個不同的模塊運行兩個線程,模塊2訪問模塊1的「set_string」以便更改「my_string」的值,但是當模塊1打印字符串時,它的空。

第一模塊:

from threading import Thread 
import Module2 as M2 
import time 

my_string = "" 


def set_string(string): 
    global my_string 
    my_string = string 


def mainloop1(): 
    global my_string 
    while True: 
     print("Module 1: ", my_string) 
     time.sleep(1) 

if __name__ == '__main__': 
    thread = Thread(target=M2.mainloop2) 
    thread.start() 
    mainloop1() 

第二模塊:

import Module1 as M1 
import time 
import random 


def mainloop2(): 
    while True: 
     string = str(random.randint(0, 100)) 
     print("Module 2: ", string) 
     M1.set_string(string) 
     time.sleep(1) 

回答

0

這是因爲該方法在不同的模塊和there are no truly global variables in python實施;在Module2中引用的set_string正在更新其globals()['M1']名稱中的my_string變量,因爲Module1正在更新直接存儲在globals()['my_string']中的my_string變量。

請注意,如果您將mainloop2的定義移動到Module1中,請更新導入和線程調用,然後獲得您的預期行爲,無限期執行順序和所有內容。

相關問題