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?