Python线程的奇怪行为

2024-03-28 23:08:45 发布

您现在位置: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没有响应。有人能解释这个行为吗


Tags: 代码importeventfalsefootimevaluedef
1条回答
网友
1楼 · 发布于 2024-03-28 23:08:45

考虑到这一点,假设我们有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个线程访问,所以它仍然是未定义的行为。你知道吗

相关问题 更多 >