奇怪的行为Python线程

时间:2015-11-04 08:56:23

标签: python multithreading python-3.x

我无法理解此代码的行为。

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 个答案:

答案 0 :(得分:0)

3想想这个,我们说我们有Thread1,Thread2和值随时间(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

正如你所看到的,如果你没有处理来自线程的资源,他们可以随时加入,即使是在麻烦开始的同一时间。

你只是处理主线程中的键盘中断,这导致挂起,因为你处理它但没有终止第二个线程,e也被2个线程接受,所以它仍然是未定义的行为。