Atomic properties can only ensure that getters and setters are safe. Let’s look at objC’s implementation of getters and setters.
//objc-accessors.mm
/ / / attribute lock
static StripedMap<spinlock_t> PropertyLocks;
/// getter
id objc_getProperty_non_gc(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) {
id *slot = (id((*)char*)self + offset);
if(! atomic)return *slot;
// Atom, use spin lock to lock
// Atomic retain release world
spinlock_t& slotlock = PropertyLocks[slot];
slotlock.lock();
id value = objc_retain(*slot);
slotlock.unlock();
return objc_autoreleaseReturnValue(value);
}
///setter
static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy.bool mutableCopy) {
/ / to omit...
if(! atomic) {// Non-atomic, no lock
oldValue = *slot;
*slot = newValue;
} else {
// Atom, use spin lock to lock
spinlock_t& slotlock = PropertyLocks[slot];
slotlock.lock();
oldValue = *slot;
*slot = newValue;
slotlock.unlock();
}
objc_release(oldValue);
}
Copy the code
You can see that spinlock_t spinlocks are used inside the getter and setter generated by the property tagged atomic to secure access to the getter and setter.
Os_unfair_lock is not a true spinlock.
The atomic feature is not absolutely thread-safe and can still be problematic in other complex multithreaded environments. For example, multi-threaded Array add and remove operations cannot ensure that the add and remove operations are executed in sequence, resulting in security problems. It is recommended to use lock to ensure thread safety.
The Next
- Common locks in iOS
- iOS OSSpinLock
- Underlying analysis of iOS Synchronized
- IOS NSLock underlying analysis
- IOS Atomic low-level analysis
Refer to the link
opensource objc4