2015-11-04 147 views
0

我無法理解此代碼的行爲。奇怪行爲Python線程

import sys 
import threading 
import time 
n = 0 
e = threading.Event() 
# q = False 

def foo(): 
    global n 
    while not e.is_set(): 
     time.sleep(2) 
     print("Value ", n) 
     n = 0 

t = threading.Thread(target=foo) 
t.start() 

while True: 
    try: 
     n += 1 
     time.sleep(1) 
    except KeyboardInterrupt: 
     e.set() 

輸出

Value 2 
Value 1 
Value 1 
Value 2 
Value 2 
Value 1 
Value 2 
Value 2 
Value 2 
Value 1 
Value 2 
Value 1 
Value 2 
Value 1 
Value 1 
Value 1 
Value 1 
^CValue 3 
^C^C^C 

當我在第一次輸入Ctrl-C。該程序不打印任何東西,並被阻止,並且不會進一步響應Ctrl-C.有人可以解釋這種行爲

+1

您正在同一時間從2個線程獲取全局資源,實際上這是未定義的行爲。 – Netwave

+0

這可能不是最佳實踐。我只是想了解這裏發生了什麼。 – user634615

+0

我會做一個答案試圖解釋 – Netwave

回答

0

3想到這一點,可以說我們有Thread1,Thread2和time值(T):

Value = 0 at Time 0 
    Value at Thread1 at Time0 is 0, it is incremented so Value = 1 
    Value at Thread2 at Time0 is 0 again because is accesed at the same time, it is incremented so Value = 1 

Value = 1 at Time 1 
    Value at Thread2 at Time1 is 1, it is incremented so Value = 2 
    Value at Thread1 at Time1 is 2 (it was incremented before the Thread1 could acces it), it is incremented so Value = 3 

正如你所看到的,如果你不從,他們可以在任何時候accesed線程訪問非常處理資源,即使在相同的時間,其中的麻煩開始。

您只是在處理主線程中的鍵盤中斷,這會導致掛起,因爲您正在處理它但不終止第二個線程,e也由2個線程處理,因此它仍然是未定義的行爲。

+1

我想知道Ctrl-C的行爲。 – user634615