美文网首页Objective-C
atomic内部使用的是自旋锁还是互斥锁?

atomic内部使用的是自旋锁还是互斥锁?

作者: lotus_yoma | 来源:发表于2020-11-25 15:12 被阅读0次

OC代码

在main.m文件中定义ZYPerson类,分别有atomic修饰的属性name和nonatomic修饰的属性gender

@interface ZYPerson : NSObject

@property (atomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;

@end

@implementation ZYPerson

@end

通过终端命令将main.m里的内容转换成c++代码
xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m

setter

先来看main.cpp中name和gender的setter方法

static void _I_ZYPerson_setName_(ZYPerson * self, SEL _cmd, NSString *name) {
    objc_setProperty (
                      self,
                      _cmd,
                      __OFFSETOFIVAR__(struct ZYPerson, _name),
                      (id)name,
                      1,
                      1);
}

static void _I_ZYPerson_setGender_(ZYPerson * self, SEL _cmd, NSString *gender) {
    objc_setProperty (
                      self,
                      _cmd,
                      __OFFSETOFIVAR__(struct ZYPerson, _gender),
                      (id)gender,
                      0,
                      1);
}

发现objc_setProperty中只有第5个参数不同,猜测跟atomic有关。
去runtime源码中搜索方法objc_setProperty,可以发现:

  • 第5个参数的确是用来判断atomic的。
  • 第6个参数shouldCopy,从实现来看是用来判断copy关键字的
#define MUTABLE_COPY 2
void objc_setProperty(id self, SEL _cmd, ptrdiff_t offset, id newValue, BOOL atomic, signed char shouldCopy) 
{
    bool copy = (shouldCopy && shouldCopy != MUTABLE_COPY);
    bool mutableCopy = (shouldCopy == MUTABLE_COPY);
    reallySetProperty(self, _cmd, newValue, offset, atomic, copy, mutableCopy);
}

objc_setProperty内部调用了真正的属性赋值方法reallySetProperty,前6个参数和objc_setProperty一致,最后一个参数用来判断shouldCopy是否等于MUTABLE_COPY=2。

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);
    }

    if (!atomic) {
        oldValue = *slot;
        *slot = newValue;
    } else {
        spinlock_t& slotlock = PropertyLocks[slot];
        slotlock.lock();
        oldValue = *slot;
        *slot = newValue;        
        slotlock.unlock();
    }

    objc_release(oldValue);
}

可以看出:不管是copy、mutableCopy、strong、retain关键词修饰的OC对象,newValue都会retain一次,copy是操作内部retain的。

  • nonatomic:1. 是将新的属性值直接赋值给对应属性; 2. release原值
  • atomic:在赋值前后进行spinlock_t加锁/解锁操作,其他操作跟nonatomic是一致的。
using spinlock_t = mutex_tt<LOCKDEBUG>;
class mutex_tt : nocopy_t {
    os_unfair_lock mLock;
}

查找源码发现spinlock_t是os_unfair_lock,是自旋锁

getter

同样getter方法也是如此,atomic修饰的属性进行加锁处理,说明atomic属性在setter和getter方法中是利用自旋锁保证线程安全的。

static NSString * _I_ZYPerson_name(ZYPerson * self, SEL _cmd) { 
    typedef NSString * _TYPE;
return (_TYPE)objc_getProperty(
    self, 
    _cmd, 
    __OFFSETOFIVAR__(struct ZYPerson, _name), 
    1); 
}
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);
}

注意:atomic保证setter和getter方法是线程安全的,但是不能保证属性在使用过程中的安全。即person.name=@"001"是安全的,但是不能保证[person.name stringByAppendingString: @"test"];也是安全的。

阅读源码过程中涉及到的其他方法

判断一个实例对象是否是TaggedPointer

#if (TARGET_OS_OSX || TARGET_OS_IOSMAC) && __x86_64__
    // 64-bit Mac - tag bit is LSB
#   define OBJC_MSB_TAGGED_POINTERS 0
#else
    // Everything else - tag bit is MSB
#   define OBJC_MSB_TAGGED_POINTERS 1
#endif

#if OBJC_MSB_TAGGED_POINTERS
#   define _OBJC_TAG_MASK (1UL<<63)
#else
#   define _OBJC_TAG_MASK 1UL
#endif

static inline bool 
_objc_isTaggedPointer(const void * _Nullable ptr)
{
    return ((uintptr_t)ptr & _OBJC_TAG_MASK) == _OBJC_TAG_MASK;
}

修改对象的isa指针指向新的Class对象

Class object_setClass(id obj, Class cls)
{
    if (!obj) return nil;
    if (!cls->isFuture()  &&  !cls->isInitialized()) {
        lookUpImpOrNil(nil, @selector(initialize), cls, LOOKUP_INITIALIZE);
    }

    return obj->changeIsa(cls);
}

相关文章

  • 多线程复习

    自旋锁 & 互斥锁 自旋锁:atomic、OSSpinLock、dispatch_semaphore_t临界区加锁...

  • atomic内部使用的是自旋锁还是互斥锁?

    OC代码 在main.m文件中定义ZYPerson类,分别有atomic修饰的属性name和nonatomic修饰...

  • 多线程

    同步锁,又叫互斥锁,@synchronized(self) 自旋锁:atomic:原子属性,多线程环境下,只有一个...

  • 自旋锁及互斥锁的概念

    原子属性 @synchronized是加互斥锁atomic实际上系统会在setter方法中加锁---自旋锁(为什么...

  • iOS面试题与核心基础之线程同步(锁,串行队列,信号量,@syn

    锁 iOS多线程锁有两类 自旋锁 和 互斥锁自旋锁与互斥锁比较类似,它们都是为了解决对某项资源的互斥使用。资源已...

  • 线程锁

    1.常见的锁包括:互斥锁,自旋锁。 2.互斥锁是指锁的类型,自旋锁是指锁的实现方式。 3.互斥锁:当上...

  • CLH并发队列

    1 什么是自旋锁和互斥锁? 由于CLH锁是一种自旋锁,那么我们先来看看自旋锁是什么? 自旋锁说白了也是一种互斥锁,...

  • IOS - 自旋锁和atomic

    本文首发于 个人博客 多线程中的锁通常分为互斥锁和自旋锁,这篇文章主要向大家介绍一些自旋锁的原理以及atomic的...

  • iOS底层探索-多线程锁

    多线程的锁大致可分为两大类:互斥锁、自旋锁;也可以分为三类:互斥锁、自旋锁、读写锁。 一、互斥锁:互斥+同步(强调...

  • iOS 锁

    同步锁 自旋锁 互斥锁

网友评论

    本文标题:atomic内部使用的是自旋锁还是互斥锁?

    本文链接:https://www.haomeiwen.com/subject/pudniktx.html