gpt4 book ai didi

python - 相同的线程标识,如何解释?

转载 作者:行者123 更新时间:2023-12-01 01:55:33 25 4
gpt4 key购买 nike

我的代码在这里,我不明白为什么线程标识是相同的数字

import threading
from werkzeug.local import Local
import time

l = Local()
l.__storage__


def add_arg(key, value):
l.__setattr__(key, value)
# time.sleep(5)


for i in range(3):
key = 'arg' + str(i)
t = threading.Thread(target=add_arg, args=(key, i))
t.start()
print(t.ident)
print(l.__storage__)

结果是:

123145354104832
123145354104832
123145354104832
{123145354104832: {'arg0': 0, 'arg1': 1, 'arg2': 2}}

然后我启用time.sleep(5),结果是:

123145311535104
123145316790272
123145322045440
{123145311535104: {'arg0': 0}, 123145316790272: {'arg1': 1}, 123145322045440: {'arg2': 2}}

任何人都可以帮我解释一下

最佳答案

根据the python docs :

Thread identifiers may be recycled when a thread exits and another thread is created.

如果没有 sleep 语句,add_arg 将在主线程再次循环之前被调用并完成。因此,每次创建新的 Python 线程时,它只是使用最近完成上一任务的系统线程(或线程 ID)。

当添加 sleep 语句时,需要一个新的系统线程(和新的 id)来启动下一个任务,因为前一个任务尚未完成。

关于python - 相同的线程标识,如何解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50244848/

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