forked from alibaba/coobjc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Coroutine.swift
304 lines (247 loc) · 7.21 KB
/
Coroutine.swift
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//
// Coroutine.swift
// coswift
//
// Copyright © 2018 Alibaba Group Holding Limited All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import Dispatch
public func co_get_swiftobj(co: UnsafeMutablePointer<coroutine_t>?) -> Coroutine? {
return co.flatMap { (coo) -> UnsafeMutableRawPointer? in
return coroutine_getuserdata(coo)
}.flatMap({ (ud) -> Coroutine? in
return Unmanaged<Coroutine>.fromOpaque(ud).takeUnretainedValue()
})
}
/**
COCoroutine is the object owned coroutine.
*/
open class Coroutine {
/**
Call back when coroutine is finished.
*/
public var finishedBlock: (() -> Void)?
/**
The code body of the coroutine.
*/
public var execBlock: () throws -> Void
/**
The `dispatch_queue_t` coroutine will run on it.
*/
public var queue: DispatchQueue
/**
The struct pointer of coroutine_t
*/
private var co: UnsafeMutablePointer<coroutine_t>?
/**
When COCoroutine as a Generator, this Channel use to yield a value.
*/
public var yieldChan: Chan<Any>?
/**
If `COCoroutine is suspend by a Channel, this pointer mark it.
*/
public var currentChan: Chan<Any>?
/**
The lastError marked in the Coroutine.
*/
public var lastError: Error?
/**
Get the current running coroutine object.
@return The coroutine object.
*/
public class func current() -> Coroutine? {
let co: UnsafeMutablePointer<coroutine_t>? = coroutine_self()
if co != nil {
return co_get_swiftobj(co: co)
} else {
return nil
}
}
/**
Tell if the coroutine is cancelled or finished.
@return isActive
*/
public class func isActive() -> Bool {
if let co = Coroutine.current() {
if co.cancelled || co.finished {
return false
} else {
return true
}
}
return false
}
/// running
private func execute() {
defer {
finished = true
if let finishBlock = finishedBlock {
finishBlock()
}
yieldChan = nil
}
do {
try self.execBlock()
} catch {
self.lastError = error
}
}
/// The c bridge
private let co_exec: @convention(c) (Optional<UnsafeMutableRawPointer>)->Void = { p in
if let co: UnsafeMutablePointer<coroutine_t> = p?.assumingMemoryBound(to: coroutine_t.self) {
if let coObj: Coroutine = co_get_swiftobj(co: co) {
coObj.execute()
}
}
}
/// Create a coroutine
///
/// - Parameters:
/// - block: the block
/// - queue: the queue
public init(block: @escaping () throws -> Void, on queue: DispatchQueue? = nil, stackSize: UInt32? = nil) {
execBlock = block
self.queue = queue ?? co_get_current_queue()
co = coroutine_create(co_exec)
if let ss = stackSize {
co?.pointee.stack_size = (ss % 16384 > 0) ? ((ss/16384 + 1)*16384) : ss
}
coroutine_setuserdata(co, Unmanaged<Coroutine>.passRetained(self).toOpaque()) { (ud) in
if let p: UnsafeMutableRawPointer = ud {
let coObj = Unmanaged<Coroutine>.fromOpaque(p).takeUnretainedValue()
coObj.co = nil
Unmanaged<Coroutine>.fromOpaque(p).release()
}
}
}
/**
The coroutine is Finished.
*/
private var finished: Bool = false
public var isFinished: Bool {
get {
return finished
}
}
private var resumed: Bool = false
/**
The coroutine is cancelled.?
*/
private var cancelled: Bool = false
public var isCancelled: Bool {
get {
return cancelled
}
}
private func performBlockOnQueue(block: @escaping ()->Void ) {
if co_get_current_queue() == self.queue {
block()
} else {
self.queue.async {
block()
}
}
}
private func internalCancel() {
if cancelled {
return
}
cancelled = true
self.co?.pointee.is_cancelled = true
if let chan = self.currentChan {
chan.cancel();
}
}
/**
Cancel the coroutine.
*/
public func cancel() {
performBlockOnQueue {
self.internalCancel()
}
}
/**
Calling this method in another coroutine. wait the coroutine to be finished.
*/
public func join() {
let chan = Chan<Bool>(buffCount: 1)
performBlockOnQueue {
if self.isFinished {
chan.send_nonblock(val: true)
} else {
self.finishedBlock = {
chan.send_nonblock(val: true)
}
}
}
do {
_ = try chan.receive()
} catch {
}
}
/**
Calling this method in another coroutine. Cancel the coroutine, and wait the coroutine to be finished.
*/
public func cancelAndJoin() {
let chan = Chan<Bool>(buffCount: 1)
performBlockOnQueue {
if self.isFinished {
chan.send_nonblock(val: true)
} else {
self.finishedBlock = {
chan.send_nonblock(val: true)
}
self.internalCancel()
}
}
do {
_ = try chan.receive()
} catch {
}
}
/**
Resume the coroutine.
@return The coroutine object.
*/
public func resume() -> Coroutine {
self.queue.async() {
if self.resumed {
return
}
self.resumed = true
coroutine_resume(self.co)
}
return self
}
/**
Resume the coroutine, if on current queue, run in current runloop.
*/
public func resumeNow() -> Void {
self.performBlockOnQueue {
if self.resumed {
return
}
self.resumed = true
coroutine_resume(self.co)
}
}
/**
Add coroutine to the scheduler. If sheduler is idle, resume it.
*/
public func addToScheduler() -> Void {
self.performBlockOnQueue {
coroutine_add(self.co)
}
}
}