Threads

Mark Charsley mark.charsley at REMOVE_THIS.radioscape.com
Wed May 22 05:46:00 EDT 2002


In article <zgsF8.571$xY.84445 at newsfep1-win.server.ntli.net>, 
r.j.cunningham at virgin.net (Robert Cunningham) wrote:

> Hopefully someone can clarify this for me, I have n threads running and 
> a global
> var c now sometimes these threads may update c (c += 1 or c -= 1). My 
> question
> is do I need to use a lock or something, at the moment I don't, I 
> assumed += is
> 'atomic' - am I right??

Very unlikely - certainly with C, += reads a memory location into a 
register, adds a value to the register, and then writes the value back to 
the memory location. Unless Python has a very odd threading system, then a 
race condition could easily occur with two threads accessing the same 
variable.

Most OS's these days come with atomic increment functions (that are 
significantly slower than +='s usual approach, which is why they aren't 
used by default). On Win32, you'll want to wrap InterlockedExchangeAdd, 
InterlockedIncrement etc., similar functions should exist on other 
platforms.

Of course it's possible that someone will reply to this mentioning a 
python package that already does this...

-- 

Mark - personal opinion only, could well be wrong, not representing 
company, don't sue us etc. etc.



More information about the Python-list mailing list