>> @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?
Nope, because the atomicity is for each property individually, not the pair of
them. The same problem occurs with any kind of atomics. Using std::atomic in
C++11? Same thing.
> 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.
Which is exactly the problem. If you use atomics, you need to understand how
they work.
But I agree that atomic / nonatomic was a bad invention. Setting a pointer is
pretty much atomic on all modern architectures. And fencing should be done by
the code using the properties. So IMHO, neither atomic nor nonatomic should
exist, and the behavior should just be a retain + autorelease without a
spinlock for the getter and just setting the retained value for the setter.
> 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!
--
Jonathan
_______________________________________________
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]