2017-10-16 49 views
0

我有一個簡單的項目,我一次顯示一個字母的消息,使用LED燈帶和我的rpi。有時LED會隨機點亮並卡住,直到顯示新消息時被清除。簡單的python多線程共享變量

我的解決方案是創建另一個線程,每2秒鐘清除一次,所以如果LED隨機打開,它們會很快關閉。

我顯然不希望該線程在消息顯示時清除顯示,所以我創建了一個全局變量來跟蹤當前是否顯示消息。

這裏的相關代碼的精簡版:

displaying = False 


def display(msg): 
    global displaying 
    displaying = True 
    for c in msg: 
     turn_all_leds_off() 
     display_char(c) 
     time.sleep(1) 
     turn_all_leds_off() 
     time.sleep(.2) 
    time.sleep(1) 
    displaying = False 


def listen_on_client(): 
    while True: 
     global displaying 
     if not displaying: 
      get_new_messages_from_server_and_display_them() 
     time.sleep(2) 


def clear_errors(): 
    while True: 
     global displaying 
     if not displaying: 
      display(" ") 
     time.sleep(2) 


t1 = Thread(target=listen_on_client, args=()) 
t2 = Thread(target=clear_errors, args=()) 
t1.start() 
t2.start() 

問題是,顯示變量似乎並沒有工作。當錯誤清除線程檢查它時,程序的行爲就好像顯示始終爲假。當我需要擔心競爭條件時,我習慣於在其他編程語言中使用鎖,但老實說,我只需要這個工作在幾秒鐘內,而不是納秒。這不是一個競爭條件,似乎變量緩存在每個線程上,並且python沒有volatile關鍵字。這與其他SO問題提出的做法類似,所以我不太清楚哪裏出了問題。有任何想法嗎?

回答

0

我已經在while循環中聲明瞭全局變量,希望避免任何緩存,但這似乎確實有相反的效果。

改變一切從

def clear_errors(): 
    while True: 
     global displaying 

def clear_errors(): 
    global displaying 
    while True: 

固定它。不知道爲什麼。