【问题标题】:the same thread ident, how to explain this?同一个线程标识,如何解释这个?
【发布时间】:2018-05-09 02:52:26
【问题描述】:

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

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}}

谁能帮我解释一下

【问题讨论】:

    标签: python werkzeug


    【解决方案1】:

    根据the python docs

    当一个线程退出并创建另一个线程时,线程标识符可能会被回收。

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

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

    【讨论】:

    • 你的回答很有用,非常感谢。
    • 欢迎来到 Stack Overflow。不要忘记“接受”(绿色勾选)回答您问题的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-11
    • 2020-05-09
    相关资源
    最近更新 更多