How to keep command line tool running with async in Swift

Issue #549

Use Semaphore

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
public class Sequence: Task {
public func run(workflow: Workflow, completion: @escaping TaskCompletion) {
let semaphore = DispatchSemaphore(value: 0)
runFirst(tasks: tasks, workflow: workflow, completion: { result in
completion(result)
semaphore.signal()
})

semaphore.wait()
}
}

public class Concurrent: Task {
public func run(workflow: Workflow, completion: @escaping (Result<(), Error>) -> Void) {
var runTaskCount = 0
let taskCount = tasks.count
let semaphore = DispatchSemaphore(value: 0)

tasks.forEach { task in
task.run(workflow: workflow, completion: { _ in
self.serialQueue.async {
runTaskCount += 1
if runTaskCount == taskCount {
completion(.success(()))
semaphore.signal()
}
}
})
}

semaphore.wait()
}
}

Read more

Comments