C
C
Coder 14482021-10-21 14:45:11
Python
Coder 1448, 2021-10-21 14:45:11

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

Question: why does the first code produce not 0 1, but 1 1?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-10-21
@wows15

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 question

Ask a Question

731 491 924 answers to any question