i++ in Python?

Peter Hansen peter at engcorp.com
Thu Jul 18 23:48:44 EDT 2002


OtisUsenet wrote:
> 
> Peter Hansen <peter at engcorp.com> wrote in message news:<3D37429C.53BC0FDB at engcorp.com>...
> > OtisUsenet wrote:
> > >
> > > Python newbie question.  How does one do something like this in
> > > Python:
> > >
> > >     # assign the value of j to i and then increment j by 1
> > >     i = j++
> >
> > Is there anything you don't like about doing it exactly as your comment
> > reads?
> 
> Yes, actually :)
> I don't like the fact that if 'j' is some kind of a global counter
> variable, and I'm dealing with multiple threads, it is then, I
> believe, possible for 2 or more threads to execute i = j at the same
> time (i.e. before 'j' had the chance to increase).
> One can probably work around this....
> ...although, now that I think about it, even i = j++ wouldn't be
> thread-safe completely, as on the machine code level this still gets
> executed in multiple steps.....I think. :)

It's even worse than that!  Even j++ is not thread-safe, and relying
on such behaviour, especially without knowing exactly how the underlying
implementation or hardware deals with it, is going to lead you into
trouble with threads.  

Whether C or Python, it's always best to use the defined mechanisms 
to implement critical sections or similar mechanisms to ensure proper 
thread safety.  Specifically with Python, you should probably be using
something like threading.RLock to gain such protection.

-Peter



More information about the Python-list mailing list