2015-11-04 81 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