iOS                
            DispatchGroup
        
        
            
    수색…
소개
소개
여러 스레드가 실행 중이라고 가정 해보십시오. 각 스레드는 하나의 작업을 수행하고 있습니다. 모든 작업 스레드가 완료되면 mainThread 또는 다른 스레드에서 알림을 받으려고합니다.
 이러한 문제에 대한 가장 간단한 해결책은 DispatchGroup 입니다. 
 DispatchGroup 사용할 때 각 요청에 대해 그룹을 enter 하고 완료된 요청마다 그룹을 leave 합니다. 
 그룹에 더 이상 요청이 없으면 notify (통지)됩니다. 
용법:
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        let dispatchGroup = DispatchGroup() //Create a group for the tasks.
        let session: URLSession = URLSession.shared
        
        dispatchGroup.enter() //Enter the group for the first task.
        
        let firstTask = session.dataTask(with: URLRequest(url: URL(string: "https://stackoverflow.com")!)) { (data, response, error) in
            
            //Process Response..
            
            dispatchGroup.leave() //Leave the group for the first task.
        }
        
        dispatchGroup.enter()  //Enter the group for the second task.
        
        let secondTask = session.dataTask(with: URLRequest(url: URL(string: "https://google.ca")!)) { (data, response, error) in
            
            //Process Response..
            
            dispatchGroup.leave()  //Leave the group for the second task.
        }
        
        
        //Get notified on the main thread/queue.. when ALL of the tasks above has been completed.
        dispatchGroup.notify(queue: DispatchQueue.main) { 
            
            print("Every task is complete")
            
        }
        
        
        //Start the tasks.
        firstTask.resume()
        secondTask.resume()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
 위와 같이하면 모든 작업이 완료 될 때 wait 무한히 wait 필요가 없습니다. 모든 작업이 시작되기 전에 로더를 표시하고 모든 작업이 완료된 후 로더를 닫을 수 있습니다. 이렇게하면 주 스레드가 차단되지 않고 코드가 깨끗하게 유지됩니다. 
 이제 작업을 ordered 하거나 배열에 응답을 순차적으로 추가하려고한다고 가정합니다. 당신은 다음을 할 수 있습니다 : 
import UIKit
//Locking mechanism..
func synchronized(_ lock: AnyObject, closure: () -> Void) {
    objc_sync_enter(lock)
    closure()
    objc_sync_exit(lock)
}
class ViewController: UIViewController {
    let lock = NSObject() //Object to lock on.
    var responseArray = Array<Data?>() //Array of responses.
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let dispatchGroup = DispatchGroup()
        let session: URLSession = URLSession.shared
        
        dispatchGroup.enter() //Enter the group for the first task.
        
        let firstTask = session.dataTask(with: URLRequest(url: URL(string: "https://stackoverflow.com")!)) { (data, response, error) in
            
            //Process Response..
            synchronized(self.lock, closure: { () -> Void in
                self.responseArray[0] = data ?? nil
            })
            dispatchGroup.leave() //Leave the group for the first task.
        }
        
        dispatchGroup.enter()  //Enter the group for the second task.
        
        let secondTask = session.dataTask(with: URLRequest(url: URL(string: "https://google.ca")!)) { (data, response, error) in
            
            //Process Response..
            
            synchronized(self.lock, closure: { () -> Void in
                self.responseArray[1] = data ?? nil
            })
            
            dispatchGroup.leave()  //Leave the group for the second task.
        }
        
        
        //Get notified on the main thread.. when ALL of the requests above has been completed.
        dispatchGroup.notify(queue: DispatchQueue.main) { 
            
            print("Every task is complete..")
            
            for i in 0..<self.responseArray.count {
                
                if self.responseArray[i] == nil {
                    print("Request #\(i) Failed.\n")
                }
                else {
                    print("Request #\(i) Succeeded.\n")
                }
            }
        }
        
        //Two tasks added to the array. Responses are assumed nil until they complete.
        self.responseArray.append(nil)
        self.responseArray.append(nil)
        
        //Start the tasks.
        firstTask.resume()
        secondTask.resume()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}
노트
 모든 항목에는 DispatchGroup 종료가 있어야합니다. entering 한 후 leave 하는 leave 잊어 버리면 스스로를 준비하고있는 것입니다. 작업이 완료되면 결코 통지되지 않습니다. 
 금액 enter 의 양이 동일해야합니다 leave . 
Modified text is an extract of the original Stack Overflow Documentation
        아래 라이선스 CC BY-SA 3.0
        와 제휴하지 않음 Stack Overflow