a questions about thread-safety of boolean variables

Charlie Dickens cdickens123 at gmail.com
Wed Sep 30 05:14:50 EDT 2009


What about dictionaries? Reading values, adding new ones and the most
important: changing an existing value - can it corrupt the state of the
dictionary or that it is guaranteed that if I try to read the value of this
key, I can only get the old one or the new one, but not something weird
instead (because a different thread changed the value while this thread was
trying to read it).
About your remark that I don't need to check if a.x is True, I do need, and
indeed it is acceptable that doSomething() will run, because this logic
resides inside a loop, and it is only important for me that it will stop
entering the loop sometime (I don't care if there are n iterations or n+1 or
even n+m)

Thanks

On Wed, Sep 30, 2009 at 10:44 AM, steve <steve at lonetwin.net> wrote:

> 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/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090930/8ec5246f/attachment.html>


More information about the Python-list mailing list