GCD总结

作者: lyhux | 来源:发表于2015-12-14 14:58 被阅读80次

概念

  同步: 阻塞当前线程的执行。(dispatch_sync)
  异步: 不会阻塞当前线程的执行。(dispatch_async)
  串行队列: 
  并行队列:

</br>

队列分为两类,串行队列和并行对列

串行队列,不能同步执行,不然会发现死锁
原因分析, 阻塞当前线程,在当前线程执行代码块,然后再继续执行当前线程的别的代码。可是当前线程已被阻塞,代码块无法执行。当前线程中的其余代码也无法执行。

总结:

串行 并行
同步 死锁 (1) 线程:当前; 阻塞: 是 (2)
异步 线程: 队列对应线程; 阻塞: 否 (3) 线程: 创建新的线程; 阻塞: 否 (4)
 对应线程: dispatch_get_main_queue对应的是主线程
          dispatch_queue_create 对应别的线程
 当前线程: 默认在主线程或在用并行队列异步执行产生的新线程

事例代码(对应表格中的编号)

(1)
(2)

let myQueue = dispatch_queue_create("lyhux_queue", DISPATCH_QUEUE_CONCURRENT)       
let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let mainQueue = dispatch_get_main_queue()
NSLog("之前 --%@", NSThread.currentThread())

dispatch_async(myQueue, {() -> Void in

    NSLog("My queue async --%@", NSThread.currentThread())

    dispatch_sync(globalQueue, {() -> Void in
        NSLog("global sync --%@", NSThread.currentThread())
    })

    dispatch_sync(globalQueue, {() -> Void in
        NSLog("global sync --%@", NSThread.currentThread())
    })

    dispatch_sync(globalQueue, {() -> Void in
        NSLog("global sync --%@", NSThread.currentThread())
    })
    dispatch_sync(globalQueue, {() -> Void in
        NSLog("global sync --%@", NSThread.currentThread())
    })

    dispatch_sync(globalQueue, {() -> Void in
        NSLog("global sync --%@", NSThread.currentThread())
    })

})
NSLog("之后 --%@", NSThread.currentThread())

(3)

let myQueue = dispatch_queue_create("lyhux_queue", DISPATCH_QUEUE_SERIAL)        
let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)       
let mainQueue = dispatch_get_main_queue()
NSLog("之前 --%@", NSThread.currentThread())

dispatch_async(globalQueue, {() -> Void in
    NSLog("global async --%@", NSThread.currentThread())
    dispatch_async(myQueue, {() -> Void in
        NSLog("What thread: %@", NSThread.currentThread())
    
        dispatch_async(mainQueue, {() -> Void in
            NSLog("Main thread: %@", NSThread.currentThread())
        })
    })
})


dispatch_async(globalQueue, {() -> Void in
    NSLog("global 2 async --%@", NSThread.currentThread())
    dispatch_async(myQueue, {() -> Void in
        NSLog("What thread 2: %@", NSThread.currentThread())    
        dispatch_async(mainQueue, {() -> Void in
            NSLog("Main thread 2 : %@", NSThread.currentThread())
        })
    })
})

dispatch_async(globalQueue, {() -> Void in
    NSLog("global 3 async --%@", NSThread.currentThread())
    dispatch_async(myQueue, {() -> Void in
        NSLog("What thread 3: %@", NSThread.currentThread())
    
        dispatch_async(mainQueue, {() -> Void in
            NSLog("Main thread 3 : %@", NSThread.currentThread())
        })
    })
})

NSLog("之后 --%@", NSThread.currentThread())

(4)

有错误欢迎指正,拍砖

详细介绍点击链接

相关文章

网友评论

      本文标题:GCD总结

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