底层

iOS-OC底层22:GCD底层探索

2020-11-06  本文已影响0人  MonKey_Money

前沿

队列的本质是对象,在我们使用GCD创建队列时,创建好的队列主要是记录并发或者串行等信息,如果需要完成任务则需要被函数调用。下面就从底层探索这些函数
我们可以在官网上下载libdispatch,如果在libdispatch中有多个判断,我们怎么确定走的哪个判断呢?我们就可以下符号断点验证。下面的确定的流程图好多都是通过下符号断点确定到底走哪个if else的。

1.同步和死锁

串行

DispatchSerialSync.png

死锁

死锁发生在串行队列同步执行,我们可以在主线程中同步主队列,看一下堆栈信息。

        NSLog(@"1234");
    });
bt后的堆栈信息
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
    frame #0: 0x00000001046d206c libdispatch.dylib`__DISPATCH_WAIT_FOR_QUEUE__ + 444
    frame #1: 0x00000001046d1a43 libdispatch.dylib`_dispatch_sync_f_slow + 231
  * frame #2: 0x0000000104450123 001---函数与队列`-[ViewController viewDidLoad](self=0x00007f8c41706ea0,
SyncLock.png
static inline bool
_dispatch_lock_is_locked_by(dispatch_lock lock_value, dispatch_tid tid)
{
    // equivalent to _dispatch_lock_owner(lock_value) == tid
    return ((lock_value ^ tid) & DLOCK_OWNER_MASK) == 0;
}

_dispatch_lock_is_locked_by主要是判断被锁的线程和当前线程是否为同一个线程,如果是同一个线程则会在DISPATCH_WAIT_FOR_QUEUE 中CRASH

并发

ConcurrentSync.png

2.异步

并发

AsyncConcurrent.png

我们着重看一下_dispatch_root_queue_poke_slow

    _dispatch_retain(dq); // released in _dispatch_worker_thread
        while ((r = pthread_create(pthr, attr, _dispatch_worker_thread, dq))) {
            if (r != EAGAIN) {
                (void)dispatch_assume_zero(r);
            }
            _dispatch_temporary_resource_shortage();
        }

对线程的创建的
在什么时候调用异步中的block呢?我们通过堆栈信息查看一下

    dispatch_queue_t concurrentqueue = dispatch_queue_create("my.con", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(concurrentqueue, ^{
        NSLog(@"1234");
    });
(lldb) bt
viewDidLoad]_block_invoke(.block_descriptor=0x0000000106c2e0f0) at ViewController.m:23:9
    frame #1: 0x0000000106e9c8ac libdispatch.dylib`_dispatch_call_block_and_release + 12
    frame #2: 0x0000000106e9da88 libdispatch.dylib`_dispatch_client_callout + 8
    frame #3: 0x0000000106ea03d6 libdispatch.dylib`_dispatch_continuation_pop + 557
    frame #4: 0x0000000106e9f7dc libdispatch.dylib`_dispatch_async_redirect_invoke + 779
    frame #5: 0x0000000106eaf5b6 libdispatch.dylib`_dispatch_root_queue_drain + 351
    frame #6: 0x0000000106eaff1b libdispatch.dylib`_dispatch_worker_thread2 + 135

我们看一下_dispatch_root_queues_init中_dispatch_worker_thread2===>_dispatch_root_queue_drain===>_dispatch_continuation_pop_inline==>dx_invoke==> _dispatch_async_redirect_invoke===>_dispatch_continuation_pop===>_dispatch_continuation_pop_inline=====>_dispatch_client_callout

3.栅栏

栅栏只能用自建的并发队列
dispatch_barrier_async===>_dispatch_continuation_async===>_dispatch_lane_concurrent_push====>_dispatch_lane_push===>_dispatch_lane_push_waiter

4.信号量

    dispatch_semaphore_t sepahore=dispatch_semaphore_create(1);
    dispatch_queue_t queue = dispatch_queue_create("1234", DISPATCH_QUEUE_CONCURRENT);
  __block  int i = 0;
    while (i<5) {
        dispatch_semaphore_wait(sepahore, DISPATCH_TIME_FOREVER);

        dispatch_async(queue, ^{
            sleep(2);
            I++;
            NSLog(@"内部的%d",i);
            dispatch_semaphore_signal(sepahore);
            
        });
        
    }
打印结果
2020-11-09 15:03:53.656294+0800 001---函数与队列[19344:6787567] 内部的1
2020-11-09 15:03:55.658937+0800 001---函数与队列[19344:6787567] 内部的2
2020-11-09 15:03:57.664476+0800 001---函数与队列[19344:6787567] 内部的3
2020-11-09 15:03:59.668310+0800 001---函数与队列[19344:6787567] 内部的4
2020-11-09 15:04:01.672977+0800 001---函数与队列[19344:6787567] 内部的5
2020-11-09 15:04:03.677596+0800 001---函数与队列[19344:6787567] 内部的6

信号量到底做了什么呢?让我们一块探究GCD的实现
1.dispatch_semaphore_create(long value)
创建一个OS_dispatch_semaphore的对象,里面保存我们设置的value值。如果value小于0,返回0
2.dispatch_semaphore_wait
对保存的value值先进行减1,如果value值大于等于0,则正常执行,如果小于0则
_dispatch_semaphore_wait_slow等待.
DISPATCH_TIME_NOW立即执行,DISPATCH_TIME_FOREVER如果不满足条件会等待。
3.dispatch_semaphore_signal
对保存的value值进行加1,如果value大于0,则正常执行,

5.单例

dispatch_once===>_dispatch_once==>(源码中的)dispatch_once===>dispatch_once_f

void
dispatch_once_f(dispatch_once_t *val, void *ctxt, dispatch_function_t func)
{
    dispatch_once_gate_t l = (dispatch_once_gate_t)val;

#if !DISPATCH_ONCE_INLINE_FASTPATH || DISPATCH_ONCE_USE_QUIESCENT_COUNTER
    uintptr_t v = os_atomic_load(&l->dgo_once, acquire);
    if (likely(v == DLOCK_ONCE_DONE)) {
        return;
    }
#if DISPATCH_ONCE_USE_QUIESCENT_COUNTER
    if (likely(DISPATCH_ONCE_IS_GEN(v))) {
        return _dispatch_once_mark_done_if_quiesced(l, v);
    }
#endif
#endif
    if (_dispatch_once_gate_tryenter(l)) {
        return _dispatch_once_callout(l, ctxt, func);
    }
    return _dispatch_once_wait(l);
}

_dispatch_once_gate_tryenter判断,确定没有被加锁,状态是DLOCK_ONCE_UNLOCKED
通过符号断点可知,_dispatch_once_callout,调用block,并调用_dispatch_once_gate_broadcast进行广播并设置DLOCK_ONCE_DONE状态。
如果在没有实例化完成时,有其他调用单例,则走_dispatch_once_wait会死循环,直到前面单例完成。

调度组

    dispatch_queue_t concurrentqueue = dispatch_queue_create("my.con", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    dispatch_async(concurrentqueue, ^{
        sleep(2);
        NSLog(@"1234");
        dispatch_group_leave(group);
    });
    dispatch_group_enter(group);
    dispatch_async(concurrentqueue, ^{
        sleep(2);
        NSLog(@"234");
        dispatch_group_leave(group);
    });
    dispatch_group_notify(group, concurrentqueue, ^{
        NSLog(@"执行结束了");
    });
打印结果
2020-11-09 17:09:07.973422+0800 001---函数与队列[91778:7107224] 1234
2020-11-09 17:09:07.973422+0800 001---函数与队列[91778:7107227] 234
2020-11-09 17:09:07.973692+0800 001---函数与队列[91778:7107227] 执行结束了

1.创建调度组dispatch_group_create
dispatch_group_create====>_dispatch_group_create_with_count(0)====>创建dispatch_group_t对象。group的value值为0
2.入组 dispatch_group_enter(group);
对group的value值减1,如果值为0则组进行retain一般不会出现这种情况。
3.出组dispatch_group_leave(group)
对group的value值加1,如果group成对出现则会唤醒dispatch_group_notify内的block
4.dispatch_group_async
dispatch_group_async====>_dispatch_continuation_group_async====>dispatch_group_enter,入组。
调用dispatch_group_asyncblock时
_dispatch_continuation_pop===》_dispatch_continuation_pop_inline====>_dispatch_continuation_invoke_inline======>_dispatch_continuation_with_group_invoke=====>dispatch_group_leave
dispatch_group_async实际上是内部实现了dispatch_group_enter和dispatch_group_leave。

补充Dispatch_Source

dispatch_source_create 创建源
dispatch_source_set_event_handler 设置源事件回调
dispatch_source_merge_data 源事件设置数据
dispatch_source_set_timer源事件设置颜色
dispatch_source_get_data 获取源事件数据
dispatch_resume 继续
dispatch_suspend 挂起
下面计时器的核心代码

 self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0    ));
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
    
    dispatch_source_set_timer(self.timer, start,  (uint64_t)(1.0 * NSEC_PER_SEC), 0);
    dispatch_source_set_event_handler(self.timer, ^{
     
        
    });
dispatch_resume(self.timer);
上一篇 下一篇

猜你喜欢

热点阅读