Issue 1339045: Threading misbehavior with lambdas (original) (raw)

suppose i write: def f(x): print x()

for i in range(3): f ( lambda : i )

I got 0,1,2

But when I write

for i in range(3): thread . start_new_thread ( f , ( lambda : i ) )

I got 2,2,2

Probably I don't get well design principles, but isn't it against thread consistency? (as long as threads does not interact with each other, interlace doesn't matter).

Logged In: YES user_id=341410

This is a bug in your understanding of lambdas, not in how threads work. More specifically, lambdas do late binding. By the time the threads have actually started executing and call the lambda, the name 'i' is bound to the value 2.

If you need early binding, then you should bind early:

for i in xrange(3): thread.start_new_thread(f, (lambda i=i:i))