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
2010-02-14 03:00:21
Thanks, Mitch. If one thread sets it to YES while another is setting it to NO, can there be memory corruption?
Jacko
2010-02-14 03:25:16
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
2010-02-14 03:33:59
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
2010-02-14 06:59:46
Thanks. I've decided to switch to int32_t instead of BOOL, and use OSAtomicAnd32Barrier and OSAtomicOr32Barrier to set and unset my flag.
Jacko
2010-02-14 22:55:24