之前一直以为两者的区别是:atomic是线程安全的,但比较损耗性能。nonatomic是线程非安全的,速度较快。
现在才知道,atomic也不是绝对的线程安全。atomic只是保证属性的set、get方法的原子性操作,只保证其读写安全,但不保证
get方法能取到正确的值,也就是线程安全。很简单一个例子:
@property(atomic,assign) int theCount;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for(inti =0; i<1000; i++) {
self.theCount++;
NSLog(@"theCount in threadA is %d",self.theCount);
}
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for(inti =0; i<1000; i++) {
self.theCount++;
NSLog(@"theCount in threadB is %d",self.theCount);
}
});
两个异步线程循环执行i++操作,打印出来的数据基本是乱的,超乎你的想象。
因为i++并不是原子操作,多线程中不能保证数据的可靠性。也就是不能保证线程安全。
网友评论