On Tue, Apr 25, 2017 at 8:53 PM Charles Srstka <[email protected]> wrote:
> On Apr 25, 2017, at 10:34 PM, Doug Hill <[email protected]> wrote: > > > A few more thoughts about atomic properties. > > I used to have weird multi-threaded strangeness with non-atomic > properties. I would see evidence of different threads having different > values of properties when it’s clear, by knowledge of the algorithm of my > code, that they shouldn’t. This different thread visibility drove me nuts > to track down. Adding the atomic attribute cleared up this problem. > > > I’d never argue that atomicity isn’t needed needed when multiple threads > are involved. But the automatic atomicity that Objective-C provides usually > isn’t even the right solution to that. Consider this object: > > @interface Person: NSObject > > @property (atomic, copy) NSString *firstName; > @property (atomic, copy) NSString *lastName; > > @end > > > Is this thread-safe? You might think it is, because of the atomic > properties, but then consider some code that logs this person’s name: > > void LogName(Person *person) { > NSLog(@“%@ %@“, person.firstName, person.lastName); > } > > > Looks okay, right? But what if the person you’re logging is Theodore > Roosevelt, 26th President of the United States, and right in between > reading the first and last name, something in another thread changes it to > Lech Kaczynski, former president of Poland? You’ll log Theodore, the change > happens, and then you’ll log Kaczynski, and you’ll end up with Theodore > Kaczynski. > > That’s right, you just created the Unabomber. > > Good job. > > Anyway, most of the time, to be properly safe you need to share a single > lock/spinlock/semaphore/dispatch queue/something between your properties, > not give each one their own. > Exactly! Atomic properties – in my experience – usually are too fine-grained for real world code. They can work well for a subset of needs but most of the time you need less granular locking to incorporate dependent logic inside of the critical section, etc. I think it is better to not use atomic properties by default and only explicitly use them when the property and clients of it can truly benefit from it. Instead proper use of coherency domains (say GCD queues), locking, and/or working with copies of data should be used in most situations when multiple threads are involved. -Shawn
_______________________________________________ Do not post admin requests to the list. They will be ignored. Objc-language mailing list ([email protected]) Help/Unsubscribe/Update your Subscription: https://lists.apple.com/mailman/options/objc-language/archive%40mail-archive.com This email sent to [email protected]
