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

三种Queue

  • main queue 主线程队列
  • global 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](http://upload-images.jianshu.io/upload_images/189984-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")```
GCD异步编程中串行和并行的区别_第1张图片
Paste_Image.png
  • 分析结果 我们发现打印的顺序乱掉,没有阻塞主线程。

  • 异步线程中并行和串行的相同点
    不会阻塞主线程

  • 异步线程中并行和串行的不同点
    串行 在一个子线程中执行 遵守先进先出的原则 并行则会创建多个子线程来执行 不遵守先进先出的原则

  • 同步串行队列

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

![Paste_Image.png](http://upload-images.jianshu.io/upload_images/189984-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](http://upload-images.jianshu.io/upload_images/189984-3930598633747676.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

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





你可能感兴趣的:(GCD异步编程中串行和并行的区别)