gpt4 book ai didi

python - Python:线程中的执行顺序

转载 作者:行者123 更新时间:2023-12-03 12:54:29 24 4
gpt4 key购买 nike

这是用于测试Threading的代码:

import threading
import time


episode = 0
lock = threading.Lock()

class Agent(threading.Thread):
def __init__(self, id):
threading.Thread.__init__(self)
self.id = id

def run(self):
global episode
while episode < 5:
with lock:
print(
"{} : episode will be changed {} -> {}".format(
self.id,
episode,
episode+1
)
)
episode += 1
print("{} : changed value -> {}".format(self.id, episode))
time.sleep(1)


if __name__ == "__main__":
agents = []
for i in range(3):
agents.append(Agent(i))

for agent in agents:
agent.start()

结果:
0 : episode will be changed 0 -> 1
0 : changed value -> 1
0 : episode will be changed 1 -> 2
0 : changed value -> 2
0 : episode will be changed 2 -> 3
0 : changed value -> 3
0 : episode will be changed 3 -> 4
0 : changed value -> 4
0 : episode will be changed 4 -> 5
0 : changed value -> 5
1 : episode will be changed 5 -> 6
1 : changed value -> 6
2 : episode will be changed 6 -> 7
2 : changed value -> 7

这是我期望的结果之一:
0 : episode will be changed 0 -> 1
0 : changed value -> 1
2 : episode will be changed 1 -> 2
2 : changed value -> 2
1 : episode will be changed 2 -> 3
1 : changed value -> 3
2 : episode will be changed 3 -> 4
2 : changed value -> 4
0 : episode will be changed 4 -> 5
0 : changed value -> 5
.
.

我不明白为什么线程id = 0首先一直连续出现...据我所知,线程的执行顺序是随机的,对吗?

我的代码有什么问题?

最佳答案

线程0首先启动,捕获锁,然后在按住锁的同时进入休眠状态。在 sleep 结束,由于退出with块而释放锁和再次获取锁的循环之间有很短的时间间隔,因此线程0极有可能再次获得锁...并且一次又一次,直到episode < 5最终为false。

删除time.sleep(1)上的缩进级别,使它作为循环的一部分而不是with块的一部分执行。然后线程0将在开始 sleep 之前释放该锁,其他线程几乎可以肯定在线程0处于 sleep 状态时获得了该锁(然后,它们有整整一秒钟的时间,而不是眨眼之间)。

关于python - Python:线程中的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46397294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com