Is it always thread-safe to use atomic?

Source: Internet
Author: User

This question is seldom met, but the answer is of course not.
Atomic added a lock in the set method, preventing multi-threading from writing to the property, causing difficult-to-predict values. But it's also just a read-write lock. and thread safety is actually worse. Look underneath.

  @interface monperson: nsobject  @property (copy) nsstring * firstName;  @property (copy) NSString * LastName; -(nsstring *) FullName;  @endThread a:p.firstname = @ "Rob "; Thread b:p.firstname = @ "Robert"; Thread a:label.string = P.firstname; //<< uh, oh--would be Robert         

But if a C is also written, D reads, D reads some random values (ABC modified values), which is not thread-safe. The best way is to use lock.

lock]; // << wait for it… … … …// Thread B now cannot access pp.firstName = @"Rob";NSString fullName = p.fullName;[p unlock];// Thread B can now access plabel.string = fullName;Thread B:[p lock]; // << wait for it… … … …// Thread A now cannot access p…[p unlock];

Atomic a big problem is that it's slow, 20 times times slower than nonatomic.
Of course, it is suggested that this numerical value change can be done by the server.

Starain Dou Bean Electric Rain

Wen/natewang (author of Jane's book)
Original link: http://www.jianshu.com/p/c40b312153c1
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Is it always thread-safe to use atomic?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.