Answer the question
In order to leave comments, you need to log in
Wrong behavior of Thread with target=lambda?
I don't know if this is a bug or if I don't understand some language features, but here are some examples.
from threading import Thread
threads = []
for i in range(2):
threads.append(
Thread(target=lambda: print(i))
)
for t in threads:
t.start()
# output:
# 1
# 1
from threading import Thread
threads = []
for i in range(2):
Thread(target=lambda: print(i)).start()
# output:
# 0
# 1
from threading import Thread
threads = []
for i in range(2):
threads.append(
Thread(target=lambda i: print(i), args=[i])
)
for t in threads:
t.start()
# output:
# 0
# 1
Answer the question
In order to leave comments, you need to log in
In your first case, the body of the stream (lambda) captures through the closure not the value of i, but a reference to i.
By the time of the start in the first case, i will have a different value.
That's why you need to use args - like in the second case. Then the value is captured - not through a closure, but through a parameter.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question