Bugs item #1339045, was opened at 2005-10-26 17:21
Message generated for change (Comment added) made by josiahcarlson
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1339045&group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Threads
Group: Python 2.4
Status: Deleted
Resolution: None
Priority: 5
Submitted By: Maciek Fijalkowski (fijal)
Assigned to: Nobody/Anonymous (nobody)
Summary: Threading misbehavior with lambdas

Initial Comment:
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).

----------------------------------------------------------------------

Comment By: Josiah Carlson (josiahcarlson)
Date: 2005-10-27 12:32

Message:
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))


----------------------------------------------------------------------

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1339045&group_id=5470
_______________________________________________
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to