2. runloop、runtime

1. Runloop


CFRunLoopRef CFRunLoopGetCurrent(void) {
    CF_EXPORT CFRunLoopRef _CFRunLoopGet0(pthread_t t) {

    // 一个 线程 对应 一个 runloop
    CFRunLoopRef loop = (CFRunLoopRef)CFDictionaryGetValue(__CFRunLoops, pthreadPointer(t));
 

  1. RunLoop 的本质是什么?

    • 就是一个 while循环,可以一直保活;
    • 内核态 => 用户态; 用户态 到 内核态的切换;
  2. Runloop和线程是什么关系?

      struct __CFRunLoop {
          pthread_t _pthread;
          CFMutableSetRef _commonModes; 
          CFMutableSetRef _commonModeItems;
          CFRunLoopModeRef _currentMode;
          CFMutableSetRef _modes;
      };
    
  3. Runloop的底层数据结构是什么样的?有几种 运行模式(mode)?每个运行模式下面的 CFRunloopMode 是哪些?他们分别是什么职责?

  • 运行模式:
    • NSDefault
    • UITracking
    • UIInitialization
    • GSEventReceive : 系统内部的,我们用不到
    • NSRunloopCommonModes
  1. Runloop 的监听状态有哪几种?
  • Entry
    • _objc_autoreleasePoolPush: -2147483647,优先级最高
  • berforeTimer
  • beforeSouce
  • beforeWaiting
    • CoreAnimation::commit (setNeedsLayout/setNeedsDisplay)
    • _objc_autoreleasePoolPop()
    • _objc_autoreleasePoolPush()
  • afterWaiting
  • exit
    • _objc_autoreleasePoolPop()
  1. Runloop 的工作流程大概是什么样的?

https://juejin.cn/post/7068159603158024228

image.png
  1. Runloop 有哪些应用?
  • 创建一个保活线程去处理一个事件
[[NSThread alloc] initWithTarget:[self class] selector:@selector(startLoop) object:nil];

+ (void)startLoop {
  @autoreleasepool {
      // 创建context
      CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
      CFRunLoopSourceRef source = CFRunLoopSourceCreate(NULL, 0, &context);
     // 创建source
      CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
      CFRelease(source);
      while (kCFRunLoopRunStopped != CFRunLoopRunInMode(
         kCFRunLoopDefaultMode, ((NSDate *)[NSDate distantFuture]).timeIntervalSinceReferenceDate, NO)) {
             NSLog(@"not reached assertion");
      }
  }
}
  • 卡顿检测
- (void)beginMonitor {
    self.isMonitoring = YES;
    //监测 CPU 消耗
    self.cpuMonitorTimer = [NSTimer scheduledTimerWithTimeInterval:3
                                                             target:self
                                                           selector:@selector(updateCPUInfo)
                                                           userInfo:nil
                                                            repeats:YES];
    //监测卡顿
    if (runLoopObserver) {
        return;
    }
    dispatchSemaphore = dispatch_semaphore_create(0); //Dispatch Semaphore保证同步
    //创建一个观察者
    CFRunLoopObserverContext context = {0,(__bridge void*)self,NULL,NULL};
    runLoopObserver = CFRunLoopObserverCreate(kCFAllocatorDefault,
                                              kCFRunLoopAllActivities,
                                              YES,
                                              0,
                                              &runLoopObserverCallBack,
                                              &context);
    //将观察者添加到主线程runloop的common模式下的观察中
    CFRunLoopAddObserver(CFRunLoopGetMain(), runLoopObserver, kCFRunLoopCommonModes);
    
    //创建子线程监控
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //子线程开启一个持续的loop用来进行监控
        while (YES) {
            // 88 毫秒的一个超时
            long semaphoreWait = dispatch_semaphore_wait(dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW, STUCKMONITORRATE * NSEC_PER_MSEC));
            if (semaphoreWait != 0) {
                if (!runLoopObserver) {
                    timeoutCount = 0;
                    dispatchSemaphore = 0;
                    runLoopActivity = 0;
                    return;
                }
                //两个runloop的状态,BeforeSources和AfterWaiting这两个状态区间时间能够检测到是否卡顿
                if (runLoopActivity == kCFRunLoopBeforeSources || runLoopActivity == kCFRunLoopAfterWaiting) {
                    //出现三次出结果
                    if (++timeoutCount < 3) {
                        continue;
                    }
//                    NSLog(@"monitor trigger");
                     // 打印堆栈
                } //end activity
            }// end semaphore wait
            timeoutCount = 0;
        }// end while
    });
    
}

2. Runtime

2.1. 数据结构

// 对象结构体
struct objc_object {
    Class _Nonnull isa;     OBJC_ISA_AVAILABILITY;
};

// 实现了 objc_object 声明方法 
struct objc_class : objc_object {
     // Class ISA; // 8字节
    Class superclass; // 8字节
    cache_t cache;    // 16字节
    class_data_bits_t bits; //  objc_class的基地址
}

// bucket => [sel => imp]
struct cache_t {
    explicit_atomic<uintptr_t> _bucketsAndMaybeMask; // 8字节
    union { // 8字节
        struct {
            explicit_atomic<mask_t>    _maybeMask; //4字节
            uint16_t                   _occupied;// 4字节
        };
        explicit_atomic<preopt_cache_t *> _originalPreoptCache;
    };
}

struct class_data_bits_t {
    uintptr_t bits; // 8字节
}

// 精简过的isa_t共用体
union isa_t 
{
    isa_t() { }
    isa_t(uintptr_t value) : bits(value) { }

    Class cls;
    uintptr_t bits;

#if SUPPORT_PACKED_ISA
# if __arm64__      
#   define ISA_MASK        0x0000000ffffffff8ULL
#   define ISA_MAGIC_MASK  0x000003f000000001ULL
#   define ISA_MAGIC_VALUE 0x000001a000000001ULL
    struct {
        uintptr_t nonpointer        : 1;
        uintptr_t has_assoc         : 1;
        uintptr_t has_cxx_dtor      : 1;
        uintptr_t shiftcls          : 33; // MACH_VM_MAX_ADDRESS 0x1000000000
        uintptr_t magic             : 6;
        uintptr_t weakly_referenced : 1;
        uintptr_t deallocating      : 1;
        uintptr_t has_sidetable_rc  : 1;   // 引用计数表
        uintptr_t extra_rc          : 19;    // 引用计数
    #       define RC_ONE   (1ULL<<45)
    #       define RC_HALF  (1ULL<<18)
    };

# elif __x86_64__     
#   define ISA_MASK        0x00007ffffffffff8ULL
#   define ISA_MAGIC_MASK  0x001f800000000001ULL
#   define ISA_MAGIC_VALUE 0x001d800000000001ULL
    struct {
        uintptr_t nonpointer        : 1;
        uintptr_t has_assoc         : 1;
        uintptr_t has_cxx_dtor      : 1;
        uintptr_t shiftcls          : 44; // MACH_VM_MAX_ADDRESS 0x7fffffe00000
        uintptr_t magic             : 6;
        uintptr_t weakly_referenced : 1;
        uintptr_t deallocating      : 1;
        uintptr_t has_sidetable_rc  : 1;
        uintptr_t extra_rc          : 8;
#       define RC_ONE   (1ULL<<56)
#       define RC_HALF  (1ULL<<7)
    };

# else
#   error unknown architecture for packed isa
# endif
#endif

image.png

字节对齐: 16字节对齐

  • malloc_size: 分配内存 16字节对齐
  • class_getInstanceSize: 真实的大小
NSObject * obj = [[NSObject alloc]init];
    NSLog(@"obj = %d,%d,%d",sizeof(obj),class_getInstanceSize([NSObject class]),malloc_size((__bridge const void *)(obj))); //8,8,16

super关键字

struct  objc_super {
    id object;
    id superClass;
};

// objc_msgSendSuper( objc_super的结构体, sel_registerName("test") )
[super  test]

2.2 方法调用

  • 先找isa指针
  • 再找superClass

下面这种图非常经典
[obj iskindof:Class]
[obj isMemberof: Class]
方法调用

image.png

2.3 原理

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • 面试题 一个NSObject对象占用多少内存?实际上分配了16个字节的存储空间给NSObject对象真正有使用的空...
    AngeloD阅读 489评论 0 0
  • 转载:http://www.cocoachina.com/ios/20150601/11970.html RunL...
    Gatling阅读 1,418评论 0 13
  • RunLoop 是 iOS 和 OSX 开发中非常基础的一个概念,这篇文章将从 CFRunLoop 的源码入手,介...
    iOS大熊猫阅读 191评论 0 0
  • 得物 KVO willchangevalue什么时候调用 键值观察通知依赖于 NSObject 的两个方法: w...
    芒果不可思议阅读 628评论 0 1
  • RunLoop的概念 一般来讲,一个线程一次只能执行一个任务,执行完成后线程就会退出。如果我们需要一个机制,让线程...
    IOS学渣阅读 447评论 1 4