简体   繁体   English

奇怪的行为Python线程

[英]Strange Behavior Python threads

I am unable to understand the behavior of this code. 我无法理解此代码的行为。

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()

Output 输出量

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

When I am typing Ctrl-C for the first time. 当我第一次输入Ctrl-C时。 the program doesn't print anything and gets blocked and doesn't respond to further Ctrl-C.Can somebody explain this behavior 该程序不会打印任何内容并且被阻止并且无法响应进一步的Ctrl-C。有人可以解释此行为

3Think of this, lets say we have the Thread1, Thread2 and value with time(T): 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

As you can see, if you dont handle acceses to resources from the threads they could be accesed at any time, even at the same time where the troubles start. 如您所见,如果您不处理来自线程的资源访问,即使在麻烦开始的同时,也可以随时访问它们。

You are only handling the keyboard interrupt in the main Thread, this cause the hanging, as you are handling it but not terminating the second thread, e is accesed by the 2 threads also so it is still undefined behaviour. 您仅在主线程中处理键盘中断,这会导致挂起,因为您正在处理它,但没有终止第二个线程,两个线程也都访问了e,因此它仍然是未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM