-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKakaLifeFreedomThread.swift
More file actions
71 lines (57 loc) · 1.91 KB
/
KakaLifeFreedomThread.swift
File metadata and controls
71 lines (57 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//
// KakaLifeFreedomThread.swift
// KakaGCD
//
// Created by 李扬 on 2020/3/23.
//
import Foundation
class KakaThread: Thread {
deinit {
print("KakaThread deinit")
}
}
@available(iOS 10, *)
public class KakaLifeFreedomThread: NSObject {
static let kLifeFreedomThreadSpecificKey = DispatchSpecificKey<Any>()
var innerThread: KakaThread?
public override init() {
self.innerThread = KakaThread.init(block: {
// 创建上下文(要初始化一下结构体)
var context: CFRunLoopSourceContext = CFRunLoopSourceContext()
// 创建source
let source: CFRunLoopSource = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context)
// 往Runloop中添加source
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, CFRunLoopMode.defaultMode);
// 启动
CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 1.0e10, false);
})
self.innerThread?.start()
}
@objc public func syncExecute(_ execute: @escaping () -> Void) {
if let t = self.innerThread {
if Thread.current == t {
execute()
} else {
self.perform(#selector(syncExecute(_:)), on: t, with: execute, waitUntilDone: true)
}
}
}
@objc public func asyncExecute(_ execute: @escaping () -> Void) {
if let t = self.innerThread {
self.perform(#selector(syncExecute(_:)), on: t, with: execute, waitUntilDone: false)
}
}
public func stop() {
if let t = self.innerThread {
self.perform(#selector(__stop), on: t, with: nil, waitUntilDone: true)
}
}
// MARK: - private method
@objc func __stop() {
CFRunLoopStop(CFRunLoopGetCurrent())
self.innerThread = nil
}
deinit {
self.stop()
}
}