Interview Questions on Concurrency, GCD, Operation Queue | Swift (Mastering Concurrency in iOS - 6)
private func testProblem1() {
let queue = DispatchQueue(label: "printNumbers")
var numbers: String = ""
for i in 50...55 {
numbers += "\(i) "
}
print(numbers)
queue.async {
var numbers: String = ""
for i in 10...15 {
numbers += "\(i) "
}
print(numbers)
}
queue.async {
var numbers: String = ""
for i in 0...5 {
numbers += "\(i) "
}
print(numbers)
}
for i in 30...35 {
numbers += "\(i) "
}
print(numbers)
}
50 51 52 53 54 55
30 31 32 33 34 35
10 11 12 13 14 15
0 1 2 3 4 5
private func testProblem2() {
let queue = DispatchQueue(label: "printNumbers", attributes: .concurrent)
var numbers: String = ""
for i in 50...55 {
numbers += "\(i) "
}
print(numbers)
queue.async {
var numbers: String = ""
for i in 10...15 {
numbers += "\(i) "
}
print(numbers)
}
queue.async {
var numbers: String = ""
for i in 0...5 {
numbers += "\(i) "
}
print(numbers)
}
numbers = ""
for i in 30...35 {
numbers += "\(i) "
}
print(numbers)
}
50 51 52 53 54 55
30 31 32 33 34 35
0 1 2 3 4 5
10 11 12 13 14 15
private func addItems(item: ItemModel) {
semaphore.wait()
if walletBalance >= item.price {
PurchaseManager.shared.buyItem(item: item, balance: walletBalance) { [weak self] success in
guard let self = self else { return }
if success {
DispatchQueue.main.async {
self.walletBalance -= item.price
self.cartBalance += item.price
self.semaphore.signal()
}
}
}
}
}
start()
, cancel()
, isAsynchronous
등 프로퍼티를 새롭게 작성한다면 해당 클래스는 비동기적으로 작동하는 오퍼레이션임class AsyncOperation: Operation {
enum State: String {
case isReady
case isExecuting
case isFinished
}
var state: State = .isReady {
willSet(newValue) {
willChangeValue(forKey: state.rawValue)
willChangeValue(forKey: newValue.rawValue)
}
didSet {
didChangeValue(forKey: oldValue.rawValue)
didChangeValue(forKey: state.rawValue)
}
}
override var isAsynchronous: Bool { true }
override var isExecuting: Bool { state == .isExecuting }
override var isFinished: Bool {
if isCancelled && state != .isExecuting { return true }
return state == .isFinished
}
override func start() {
guard !isCancelled else {
state = .isFinished
return
}
state = .isExecuting
main()
}
override func cancel() {
state = .isFinished
}
}