Tanner
Tanner

Reputation: 55

the same thread ident, how to explain this?

my code is here, I can not understand why the thread ident is the same number

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__)

the result is :

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

Then I enable time.sleep(5), then the result is :

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

anyone can help my to explain this

Upvotes: 3

Views: 949

Answers (1)

selbie
selbie

Reputation: 104559

As per the python docs:

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

Without the sleep statement, add_arg is getting invoked and completed before the main thread loops around again. Hence, each time you create a new Python thread, it's simply using the system thread (or thread id) of the one that most recently completed the previous task.

When you add the sleep statement, a new system thread (and new id) is needed to start the next task because the previous one has not completed.

Upvotes: 5

Related Questions