GCD异步编程中串行和并行的区别

2016-07-19  本文已影响130人  952625a28d0d

三种Queue

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
            
        }```

- 自定义队列
- 创建一个串行和并行队列

```swift
let serial_queue: dispatch_queue_t! = dispatch_queue_create("www.baidu.com", DISPATCH_QUEUE_SERIAL)

 let concurrent_queue: dispatch_queue_t! = dispatch_queue_create("www.baidu.com", DISPATCH_QUEUE_CONCURRENT)```

- 异步串行队列

```swift
for index in 1...10 {
            dispatch_async(serial_queue, {
                print(index)
            })
        }
        
        print("Running on main thread")```

![Paste_Image.png](https://img.haomeiwen.com/i189984/bb6441dd73c87b1a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 分析打印结果 得知
首先串行队列没有阻塞主线程,然后串行队列一次打印了我们想要的结果,符合预期

- 异步并行队列

for index in 1...10 {
dispatch_async(concurrent_queue, {
print(index)
})
}

    print("running on main thread")```
Paste_Image.png
for index in 1...10 {
            dispatch_sync(serial_queue, {
                print(index)
            })
        }
        
        print("Running on main thread")```

![Paste_Image.png](https://img.haomeiwen.com/i189984/476006e260feb51a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 同步并行队列

```swift
 for index in 1...10 {
            dispatch_sync(concurrent_queue, {
                print(index)
            })
        }
        
        print("running on main thread")```

![Paste_Image.png](https://img.haomeiwen.com/i189984/3930598633747676.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

- 得出结论 
同步串行队列,只会在主线程中执行,会阻塞主线程
同步并行队列,也是只会在主线程进行,并不新建子线程,同样阻塞了主线程





上一篇下一篇

猜你喜欢

热点阅读