- Operation을 전달한다.
- 클로저를 전달한다.
- Operatoin의 배열을 전달한다.
waitUntilAllOperationsAreFinished
라는 메소드를 볼 수 있다. 이는 현재의 스레드를 operation 작동이 완료되기 전까지 멈추게 된다. 즉, wait을 block으로 이해하면 쉽다. // operationQueue 생성
let printQueue = OperationQueue()
// 사용할 최대의 쓰레드 갯수 정의(기본 설정 -1) -> 알아서
// 1 -> 시리얼
printQueue.maxConcurrentOperationCount = 2
// 간단한 클로저를 오퍼레이션 큐에 더함 (더하게 되면, 바로 작업이 비동기적으로 시작)
// 주로, 'operation'을 'operationQueue'에 넣어서 작업을 실행시키겠지만, 단순하게 클로저 가능
printQueue.addOperation { print("Test")
sleep(2)}
printQueue.addOperation { print("Test")
sleep(2)}
printQueue.addOperation { print("Test")
sleep(2)}
printQueue.addOperation { print("Test")
sleep(2)}
printQueue.waitUntilAllOperationsAreFinished()
print("OuterTest")
// Test
// Test
// Test
// Test
// OuterTest
isSuspended
속성을 true로 설정하여 OperationQueue를 일시 중지할 수 있다. 실행 중인 작업은 계속 실행되지만, 새로 추가된 작업은 isSuspended
를 다시 false로 변경하기 전까지 예약되지 않는다. maxConcurrentOperationCount
속성을 설정하면 된다. maxConcurrentOperationCount
를 1로 설정하면 실질적으로 serial queue를 생성한 것이다. let queue = OperationQueue()
queue.underlyingQueue = .global()
주요 기능 | 설명 |
---|---|
작업 추가 | OperationQueue에 Operation 객체를 추가하거나, 클로저 또는 Operation 객체의 배열을 전달하여 작업을 추가할 수 있다. |
동시성 제어 | maxConcurrentOperationCount 속성을 사용하여 동시에 실행할 수 있는 작업의 최대 수를 설정할 수 있다. 이를 통해서 동시성을 제어하고, 필요한 경우 순차적으로 작업을 실행할 수 있다. |
작업 의존성 | 작업 간의 의존성을 추가하여 특정 작업이 다른 작업이 완료된 후에만 실행되도록 할 수 있다, 이를 통해 복잡한 작업 흐름을 관리할 수 있다. |
작업 취소 | OperationQueue의 cancelAllOperations() 메소드를 사용하여 큐에 있는 모든 작업을 취소할 수 있다. 또한 개별 작업의 cancel() 메소드를 호출하여 특정 작업을 취소할 수도 있다. |
작업 대기 및 완료 | waitUntilAllOperationsAreFinished() 메소드를 사용하여 큐의 모든 작업이 완료될 때까지 현재 스레드를 차단할 수 있다. 그러나 이 메소드는 메인 UI 스레드에서 호출해서는 안 되며, 대신 직렬 DispatchQueue에서 호출해야 한다. |
class TiltShiftTableViewController: UITableViewController {
private let queue = OperationQueue()
private let context = CIContext()
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "normal", for: indexPath) as! PhotoCell
let image = UIImage(named: "\(indexPath.row).png")!
let op = TiltShiftOperation(image: image)
op.completionBlock = {
DispatchQueue.main.async {
guard let cell = tableView.cellForRow(at: indexPath) as? PhotoCell else { return }
cell.isLoading = false
cell.display(image: op.outputImage)
}
}
queue.addOperation(op)
}
}
제가 학습한 내용을 요약하여 정리한 것입니다. 내용에 오류가 있을 수 있으며, 어떠한 피드백도 감사히 받겠습니다.
감사합니다.