views:

359

answers:

1

What happens when two threads set a BOOL to YES "at the same time"?

+1  A: 

No. Without a locking construct, reading/writing any type variable is NOT atomic in Objective C.

If two threads write YES at the same time to a BOOL, the result is YES regardless of which one gets in first.

Please see: Synchronizing Thread Execution

Mitch Wheat
Thanks, Mitch. If one thread sets it to YES while another is setting it to NO, can there be memory corruption?
Jacko
http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/Multithreading/ThreadSafety/ThreadSafety.html gives a very thorough discussion. I think I will use an int instead of a BOOL, and use the OSAtomic operations on this int.
Jacko
The implication of your question is whether or not some other chunk of memory might be crunched. No; that can't happen. The worst that'll happen is you'll read a NO seemingly after you wrote a YES in another thread.
bbum
Thanks. I've decided to switch to int32_t instead of BOOL, and use OSAtomicAnd32Barrier and OSAtomicOr32Barrier to set and unset my flag.
Jacko