您的当前位置:首页正文

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_SERIAL)

 let concurrent_queue: dispatch_queue_t! =  DISPATCH_QUEUE_CONCURRENT)```

- 异步串行队列

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



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

- 异步并行队列

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")```



- 同步并行队列

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



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