> 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.
Charles
_______________________________________________
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]