奇怪的python线程输出 [英] Strange python threading output
问题描述
为我提供了一个简单的python程序进行分析.它工作正常,并随机输出13、14和15(当然).我可以看到为什么打印13和14,但是我不知道15的来源.
I was given a simple python program to analyze. It works fine, and outputs 13, 14, and 15 randomly (of course). I can see why 13 and 14 where printed, but I don't understand where 15 came from.
请解释.
from threading import Thread
import random
import time
import sys
def rwait():
amt = random.uniform(0.01,0.1)
time.sleep(amt)
x = 0
key = True
def lockx():
global key
while not key:
time.sleep(0)
rwait()
key = False
def unlockx():
global key
key = True
def A():
global x
rwait()
lockx()
reg = x
reg = reg+1
rwait()
x = reg
unlockx()
def B():
global x
rwait()
lockx()
reg = x
reg = reg+2
rwait()
x = reg
unlockx()
def main():
global x
x = 12
p1 = Thread(target=B)
p1.start()
A()
p1.join()
print("x=",x)
for k in range(20):
main()
推荐答案
可能发生三种不同的情况:
Three different things can happen:
-
线程A和B在更改之前先读取
x
,然后
-
线程A写入其结果(13),并且
thread A writes its result (13), and
线程B写入其结果(14),
thread B writes its result (14),
和第二个写胜利的线程.
and the second thread to write wins.
线程A或B首先读取x
,在另一个线程读取之前,和写入.结果:15,因为A读12,加1并写13,然后B读13并写15,反之亦然.
thread A or B reads x
first, and writes before the other thread reads. Result: 15, as either A reads 12, adds one and writes 13, then B reads 13 and writes 15, or vice-versa.
这篇关于奇怪的python线程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!