a questions about thread-safety of boolean variables
steve at lonetwin.net
Wed Sep 30 10:44:27 CEST 2009
On 09/30/2009 01:53 PM, Charlie Dickens wrote:
> if I have a class A that contains a boolean variable named x, is it safe
> to read and change it from different threads without using locks?
> Is it guaranteed that A.x will be always True or False, and not any
> other weird value that that causes it to be inconsistent (assuming I
> only set it to True or False) ?
The guarantee for A.x being only True or False, is independent of whether you
use locks or not. It depends entirely on code that assigns to A.x.
> I have a = A()
> first thread does:
> if a.x is True :
> 2nd thread does:
> a.x = False
> is it safe?
what if you have code like this:
if a.x is True:
a.x == False
..and thread 2 executes *after* thread 1's 'if' condition but *before*
doSomething(). If that behavior is acceptable in your application, you possibly
don't even need a.x.
> and what if x was a dict ? especially if the only values that are set in
> the dictionary are simple: booleans, integers, floats, strings
Same logic applies.
random non tech spiel: http://lonetwin.blogspot.com/
tech randomness: http://lonehacks.blogspot.com/
what i'm stumbling into: http://lonetwin.stumbleupon.com/
More information about the Python-list