a questions about thread-safety of boolean variables

steve steve at lonetwin.net
Wed Sep 30 04:44:27 EDT 2009


Hi,

On 09/30/2009 01:53 PM, Charlie Dickens wrote:
> Hi,
> 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 :
>      pass
>
> 2nd thread does:
> a.x = False
>
> is it safe?

what if you have code like this:

Thread 1
if a.x is True:
     doSomething()

Thread 2
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.

hth,
cheers,
- steve

-- 
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 mailing list