GCD死锁

一直想写一篇关于GCD死锁问题的文章, 但是后来发现了一篇文章讲得很好, 还是直接转载吧(但是把OC改为Swift 3了, 并添加了一个案例). 原文作者: brighttj(@saitjr)

死锁一直都是在使用多线程时,需要注意的一个问题。以前对同步、异步,串行、并行只有一个模糊的概念,想想也是时候整理一下了。再看看之前的博客,已经很久没有干货了【说得好像之前有干货一样】,所以,这篇博客,我尽最大努力,也借鉴了很多其他博客中的例子,来讲解GCD死锁问题。

串行与并行

在使用GCD的时候,我们会把需要处理的任务放到Block中,然后将任务追加到相应的队列里面,这个队列,叫做Dispatch Queue。然而,存在于两种Dispatch Queue,一种是要等待上一个执行完,再执行下一个的Serial Dispatch Queue,这叫做串行队列;另一种,则是不需要上一个执行完,就能执行下一个的Concurrent Dispatch Queue,叫做并行队列。这两种,均遵循FIFO原则。

举一个简单的例子,在三个任务中输出1、2、3,串行队列输出是有序的1、2、3,但是并行队列的先后顺序就不一定了。

那么,并行队列又是怎么在执行呢?

虽然可以同时多个任务的处理,但是并行队列的处理量,还是要根据当前系统状态来。如果当前系统状态最多处理2个任务,那么1、2会排在前面,3什么时候操作,就看1或者2谁先完成,然后3接在后面。

串行和并行就简单说到这里,关于它们的技术点其实还有很多,可以自行了解。

同步与异步

串行与并行针对的是队列,而同步与异步,针对的则是线程。最大的区别在于,同步线程要阻塞当前线程,必须要等待同步线程中的任务执行完,返回以后,才能继续执行下一任务;而异步线程则是不用等待。

仅凭这几句话还是很难理解,所以之后准备了很多案例,可以边分析边理解。

GCD API

GCD API很多,这里仅介绍本文用到的。

1.系统标准提供的两个队列

1
2
3
4
5
6
7
// 全局队列,也是一个并行队列
DispatchQueue.global()
// 主队列,在主线程中运行,因为主线程只有一个,所以这是一个串行队列
DispatchQueue.main

2.除此之外,还可以自己生成队列

1
2
3
4
5
// 默认是串行队列
DispatchQueue(label: "com.demo.serialQueue")
// 这是一个并行队列
DispatchQueue(label: "com.demo.concurrentQueue", attributes: .concurrent)

3.接下来是同步与异步线程的创建:

1
2
3
queue.sync {...} // 同步线程
queue.async {...} // 异步线程

案例与分析

假设你已经基本了解了上面提到的知识,接下来进入案例讲解阶段。

案例一:

1
2
3
4
5
6
7
print(1) // 任务1
DispatchQueue.main.sync {
print(2) // 任务2
}
print(3) // 任务3

结果,控制台输出:

1
1

分析

1
2
3
4
5
.sync表示是一个同步线程;
DispatchQueue.main 表示运行在主线程中的主队列;
任务2是同步线程的任务。

首先执行任务1,这是肯定没问题的,只是接下来,程序遇到了同步线程,那么它会进入等待,等待任务2执行完,然后执行任务3。但这是队列,有任务来,当然会将任务加到队尾,然后遵循FIFO原则执行任务。那么,现在任务2就会被加到最后,任务3排在了任务2前面,问题来了:

任务3要等任务2执行完才能执行,任务2由排在任务3后面,意味着任务2要在任务3执行完才能执行,所以他们进入了互相等待的局面。【既然这样,那干脆就卡在这里吧】这就是死锁。

deadlock1

案例二:

1
2
3
4
5
6
7
print(1) // 任务1
DispatchQueue.global(qos: .userInitiated).sync {
print(2) // 任务2
}
print(3) // 任务3

结果,控制台输出:

1
2
3
4
5
1
2
3

分析:

首先执行任务1,接下来会遇到一个同步线程,程序会进入等待。等待任务2执行完成以后,才能继续执行任务3。从dispatch_get_global_queue可以看出,任务2被加入到了全局的并行队列中,当并行队列执行完任务2以后,返回到主队列,继续执行任务3。

deadlock2

案例三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
let queue = DispatchQueue(label: "com.demo.serialQueue")
print(1) // 任务1
queue.async {
print(2) // 任务2
queue.sync {
print(3) // 任务3
}
print(4) // 任务4
}
print(5) // 任务5

结果,控制台输出:

1
2
3
4
5
6
7
1
5
2
// 5和2的顺序不一定

分析:

这个案例没有使用系统提供的串行或并行队列,而是自己通过DispatchQueue(label: “”)函数创建了一个的串行队列。


执行任务1;


遇到异步线程,将【任务2、同步线程、任务4】加入串行队列中。因为是异步线程,所以在主线程中的任务5不必等待异步线程中的所有任务完成;


因为任务5不必等待,所以2和5的输出顺序不能确定;


任务2执行完以后,遇到同步线程,这时,将任务3加入串行队列;


又因为任务4比任务3早加入串行队列,所以,任务3要等待任务4完成以后,才能执行。但是任务3所在的同步线程会阻塞,所以任务4必须等任务3执行完以后再执行。这就又陷入了无限的等待中,造成死锁。

deadlock3

案例四:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
print(1) // 任务1
DispatchQueue.global(qos: .userInitiated).async {
print(2) // 任务2
DispatchQueue.main.sync {
print(3) // 任务3
}
print(4) // 任务4
}
print(5) // 任务5

结果,控制台输出:

1
2
3
4
5
6
7
8
9
10
11
1
2
5
3
4
// 5和2的顺序不一定

分析:

首先,将【任务1、异步线程、任务5】加入Main Queue中,异步线程中的任务是:【任务2、同步线程、任务4】。

所以,先执行任务1,然后将异步线程中的任务加入到Global Queue中,因为异步线程,所以任务5不用等待,结果就是2和5的输出顺序不一定。

然后再看异步线程中的任务执行顺序。任务2执行完以后,遇到同步线程。将同步线程中的任务加入到Main Queue中,这时加入的任务3在任务5的后面。

当任务3执行完以后,没有了阻塞,程序继续执行任务4。

从以上的分析来看,得到的几个结果:1最先执行;2和5顺序不一定;4一定在3后面

deadlock4

案例五:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
DispatchQueue.global(qos: .userInitiated).async {
print(1) // 任务1
DispatchQueue.main.sync {
print(2) // 任务2
}
print(3) // 任务3
}
print(4) // 任务4
while true {
}
print(5) // 任务5

结果,控制台输出:

1
2
3
4
5
1
4
// 1和4的顺序不一定

分析:

和上面几个案例的分析类似,先来看看都有哪些任务加入了Main Queue:【异步线程、任务4、死循环、任务5】。

在加入到Global Queue异步线程中的任务有:【任务1、同步线程、任务3】。

第一个就是异步线程,任务4不用等待,所以结果任务1和任务4顺序不一定。

任务4完成后,程序进入死循环,Main Queue阻塞。但是加入到Global Queue的异步线程不受影响,继续执行任务1后面的同步线程。

同步线程中,将任务2加入到了主线程,并且,任务3等待任务2完成以后才能执行。这时的主线程,已经被死循环阻塞了。所以任务2无法执行,当然任务3也无法执行,在死循环后的任务5也不会执行。

最终,只能得到1和4顺序不定的结果。

deadlock5

案例六:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
print(0)
DispatchQueue.main.async {
DispatchQueue.main.async {
print("sleep 4s...")
sleep(4)
print(1)
}
print(2)
DispatchQueue.main.async {
print(3)
}
}
print(4)
print("sleep 8s...")
sleep(8)

结果,控制台输出:

1
2
3
4
5
6
7
0
4
sleep 8s...
2
sleep 4s...
1
3

分析:

首先执行print(0), 然后主队列添加异步任务, 不阻塞, 所以执行print(4), 及sleep(8)阻塞, 然后再刚才的异步任务内, 同样也是先执行print(2), 然后再执行队列中的sleep(4), print(1), print(3).

iOS 3D touch

简单介绍一下iOS中的3Dtouch. 一般开发中主要有三种情境使用:
icon的3Dtouch
应用内的预览
再就是可能游戏中会用到的按压力度的检测了

icon的3D touch

第一种方式: 在info.plist中添加

3Dtouch with info.plist

效果如下

解释一下其中的一些key的意思:
UIApplicationShortcutItemIconType 是使用系统提供的图标, 目前提供了近30种图标
UIApplicationShortcutItemIconFile 是 .xcassets 文件中自定义的图标
UIApplicationShortcutItemType 是应用通过3Dtouch启动时传给应用内部的表示, 让内部代码知道点击的是哪个item.
其他的key显而易见, 不做解释.

那么接下来就是在代码中处理3Dtouch事件了:
1.首先应用第一次启动:

1
2
3
4
5
6
7
8
var launchedShortcutItem: UIApplicationShortcutItem?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] {
launchedShortcutItem = shortcutItem as? UIApplicationShortcutItem
}
return true
}

2.应用已经启动, 并从后台3Dtouch启动:

1
2
3
4
5
6
7
func application(_ application: UIApplication,
performActionFor shortcutItem: UIApplicationShortcutItem,
completionHandler: @escaping (Bool) -> Void) {
let handleAction = handleShortcutItem(shortcutItem)
completionHandler(handleAction)
}

通过以上两种方式都获取了shortcutItem的信息, 就可以进行相应的逻辑处理了.

用代码动态添加shortcutItem

1
2
3
4
5
6
7
let item = UIApplicationShortcutItem(type: "two",
localizedTitle: "Phoenix",
localizedSubtitle: "Make a Call",
icon: UIApplicationShortcutIcon(type: .cloud),
userInfo: nil)
UIApplication.shared.shortcutItems = [item]

注意: 通过info.plist 和 代码添加的shortcutItem 并不冲突, 取并集, 但系统限制最多能够显示4个item, 因此会自动按顺序截取前4个.

应用内预览

先看一下效果图

peek & pop

peek是由一个能响应事件的view触发的, 需要在viewDidLoad中注册代理和来源视图:

1
2
3
4
override func viewDidLoad() {
super.viewDidLoad()
self.registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: self.view)
}

然后是遵守协议和实现协议方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
// 返回目标控制器
let indexPath = self.tableView.indexPathForRow(at: location)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let content = storyboard.instantiateViewController(withIdentifier: "ContentViewController") as! ContentViewController
guard indexPath != nil else {
return nil
}
return content
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
self.showDetailViewController(viewControllerToCommit, sender: self)
}

peek quick actions

在目标控制器实现以下方法:

1
2
3
4
5
6
override var previewActionItems: [UIPreviewActionItem] {
let action = UIPreviewAction(title: "Save", style: .default) { (action: UIPreviewAction, controller: UIViewController) in
print("Save image")
}
return [action]
}

按压力度监听

实现了一个小demo


代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
self.centerPoint = touch?.location(in: touch?.view)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
let force = touch?.force
let maximumPossibleForce = touch?.maximumPossibleForce
let quotient = force! / maximumPossibleForce!
let border = self.view.frame.size.width
self.round.layer.cornerRadius = border * 0.5 * quotient
self.round.frame = CGRect(x: 0, y: 0, width: border * quotient, height: border * quotient)
let point = touch?.location(in: touch?.view)
self.round.center = point!
let weight = 415 * quotient
self.weightLabel.text = "\(weight) g"
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
self.round.frame = CGRect.zero
self.weightLabel.text = "0 g"
}

本文完整demo (3Dtouch不支持模拟器, 请以真机调试)

__原创文章, 转载请注明出处

Hello World

Hello, This is my first post!