atomic很少被用到,iOS开发中属性声明经常使用nonatomic,网上很多文章提到atomic会损耗性能,但是为何会损耗性能呢?回答这个问题之前要搞清楚atomic是什么东西。
atomic是什么?为什么会损耗性能?
笔者使用objc-709源码,添加测试的target,在main函数里添加如下代码,然后进行断点调试。
#import <Foundation/Foundation.h>
@interface AtomicTest : NSObject
@property(atomic)NSString * name;
@end
@implementation AtomicTest
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
AtomicTest * atomic = [[AtomicTest alloc] init];
atomic.name = @"atomic";
}
return 0;
}
依次跳入以下代码
void objc_setProperty_atomic(id self, SEL _cmd, id newValue, ptrdiff_t offset)
{
reallySetProperty(self, _cmd, newValue, offset, true, false, false);
}
static inline void reallySetProperty(id self, SEL _cmd, id newValue, ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
{
if (offset == 0) {
object_setClass(self, newValue);
return;
}
id oldValue;
id *slot = (id*) ((char*)self + offset);
if (copy) {
newValue = [newValue copyWithZone:nil];
} else if (mutableCopy) {
newValue = [newValue mutableCopyWithZone:nil];
} else {
if (*slot == newValue) return;
newValue = objc_retain(newValue);
}
//从参数可以看出atomic是一个bool值。
if (!atomic) {
oldValue = *slot;
*slot = newValue;
} else {
spinlock_t& slotlock = PropertyLocks[slot];
slotlock.lock();
oldValue = *slot;
*slot = newValue;
slotlock.unlock();
}
objc_release(oldValue);
}
通过查看源码,atomic是什么已经很清晰:atomic是一个bool值,bool 为 true 则对赋值操作加锁。为false则不进行加锁其实就是nonatomic。
atomic为true时候使用了哪种锁进行加锁?
有文章说是@synchronized文章链接,不知从哪看的。
评论里说是自旋锁,看看spinlock_t 名字的确像是自旋锁。但是YYKit作者文章说自旋锁已经不再安全了文章链接。
查看spinlock_t定义
using spinlock_t = mutex_tt<DEBUG>;
看名字又成了互斥锁。苹果看来已经放弃使用自旋锁了。
class mutex_tt : nocopy_t {
os_unfair_lock mLock;
public:
mutex_tt() : mLock(OS_UNFAIR_LOCK_INIT) {
lockdebug_remember_mutex(this);
}
mutex_tt(const fork_unsafe_lock_t unsafe) : mLock(OS_UNFAIR_LOCK_INIT) { }
void lock() {
lockdebug_mutex_lock(this);
os_unfair_lock_lock_with_options_inline
(&mLock, OS_UNFAIR_LOCK_DATA_SYNCHRONIZATION);
}
void unlock() {
lockdebug_mutex_unlock(this);
os_unfair_lock_unlock_inline(&mLock);
}
void forceReset() {
lockdebug_mutex_unlock(this);
bzero(&mLock, sizeof(mLock));
mLock = os_unfair_lock OS_UNFAIR_LOCK_INIT;
}
void assertLocked() {
lockdebug_mutex_assert_locked(this);
}
void assertUnlocked() {
lockdebug_mutex_assert_unlocked(this);
}
// Address-ordered lock discipline for a pair of locks.
static void lockTwo(mutex_tt *lock1, mutex_tt *lock2) {
if (lock1 < lock2) {
lock1->lock();
lock2->lock();
} else {
lock2->lock();
if (lock2 != lock1) lock1->lock();
}
}
static void unlockTwo(mutex_tt *lock1, mutex_tt *lock2) {
lock1->unlock();
if (lock2 != lock1) lock2->unlock();
}
};
template <bool Debug>
class recursive_mutex_tt : nocopy_t {
pthread_mutex_t mLock;
public:
recursive_mutex_tt() : mLock(PTHREAD_RECURSIVE_MUTEX_INITIALIZER) {
lockdebug_remember_recursive_mutex(this);
}
recursive_mutex_tt(const fork_unsafe_lock_t unsafe)
: mLock(PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
{ }
void lock()
{
lockdebug_recursive_mutex_lock(this);
int err = pthread_mutex_lock(&mLock);
if (err) _objc_fatal("pthread_mutex_lock failed (%d)", err);
}
void unlock()
{
lockdebug_recursive_mutex_unlock(this);
int err = pthread_mutex_unlock(&mLock);
if (err) _objc_fatal("pthread_mutex_unlock failed (%d)", err);
}
void forceReset()
{
lockdebug_recursive_mutex_unlock(this);
bzero(&mLock, sizeof(mLock));
mLock = pthread_mutex_t PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
}
bool tryUnlock()
{
int err = pthread_mutex_unlock(&mLock);
if (err == 0) {
lockdebug_recursive_mutex_unlock(this);
return true;
} else if (err == EPERM) {
return false;
} else {
_objc_fatal("pthread_mutex_unlock failed (%d)", err);
}
}
void assertLocked() {
lockdebug_recursive_mutex_assert_locked(this);
}
void assertUnlocked() {
lockdebug_recursive_mutex_assert_unlocked(this);
}
};
可以看到底层是使用了os_unfair_lock来进行加锁。
/*!
* @typedef os_unfair_lock
*
* @abstract
* Low-level lock that allows waiters to block efficiently on contention.
*
* In general, higher level synchronization primitives such as those provided by
* the pthread or dispatch subsystems should be preferred.
*
* The values stored in the lock should be considered opaque and implementation
* defined, they contain thread ownership information that the system may use
* to attempt to resolve priority inversions.
*
* This lock must be unlocked from the same thread that locked it, attemps to
* unlock from a different thread will cause an assertion aborting the process.
*
* This lock must not be accessed from multiple processes or threads via shared
* or multiply-mapped memory, the lock implementation relies on the address of
* the lock value and owning process.
*
* Must be initialized with OS_UNFAIR_LOCK_INIT
*
* @discussion
* Replacement for the deprecated OSSpinLock. Does not spin on contention but
* waits in the kernel to be woken up by an unlock.
*
* As with OSSpinLock there is no attempt at fairness or lock ordering, e.g. an
* unlocker can potentially immediately reacquire the lock before a woken up
* waiter gets an opportunity to attempt to acquire the lock. This may be
* advantageous for performance reasons, but also makes starvation of waiters a
* possibility.
*/
OS_UNFAIR_LOCK_AVAILABILITY
typedef struct os_unfair_lock_s {
uint32_t _os_unfair_lock_opaque;
} os_unfair_lock, *os_unfair_lock_t;
重点关注下面一句
The values stored in the lock should be considered opaque and implementation defined, they contain thread ownership information that the system may use to attempt to resolve priority inversions.
锁里面包含线程线程所有权信息来解决优先级反转问题。所以,这块用的已经不是自旋锁。是一个叫做os_unfair_lock 的低级锁。
atomic一定是线程安全吗?
从上面源码中看出,atomic 为 true 时候会对setter进行加锁,下面getter也是一样。
id objc_getProperty(id self, SEL _cmd, ptrdiff_t offset, BOOL atomic) {
if (offset == 0) {
return object_getClass(self);
}
// Retain release world
id *slot = (id*) ((char*)self + offset);
if (!atomic) return *slot;
// Atomic retain release world
spinlock_t& slotlock = PropertyLocks[slot];
slotlock.lock();
id value = objc_retain(*slot);
slotlock.unlock();
// for performance, we (safely) issue the autorelease OUTSIDE of the spinlock.
return objc_autoreleaseReturnValue(value);
}
这种操作只能保证getter和setter是线程安全的。但是日常开发过程中,很多都是复合操作,比如下面代码
self.a = self.a + 1 ;//此操作包含getter、setter、加操作。atomic只是给单个getter、setter操作加锁了,无法保证这种复合操作的线程安全。如果要实现线程安全需要额外加锁。
[lock lock];
self.a = self.a + 1 ;
[lock unlock];
如有错误和不足之处还望指正。文字有点少,都是粘贴代码了,多多包涵。