When to use Semaphore instead of Dispatch Group?

前端 未结 4 2047
无人及你
无人及你 2021-01-30 07:16

I would assume that I am aware of how to work with DispatchGroup, for understanding the issue, I\'ve tried:

class ViewController: UIViewController {
    override         


        
4条回答
  •  忘了有多久
    2021-01-30 08:03

    Use a semaphore to limit the amount of concurrent work at a given time. Use a group to wait for any number of concurrent work to finish execution.

    In case you wanted to submit three jobs per queue it should be

    func performUsingGroup() {
        let dq1 = DispatchQueue.global(qos: .default)
        let dq2 = DispatchQueue.global(qos: .default)
        let group = DispatchGroup()
    
        for i in 1...3 {
            group.enter()
            dq1.async {
                print("\(#function) DispatchQueue 1: \(i)")
                group.leave()
            }
        }
        for i in 1...3 {
            group.enter()
            dq2.async {
                print("\(#function) DispatchQueue 2: \(i)")
                group.leave()
            }
        }
    
        group.notify(queue: DispatchQueue.main) {
            print("done by group")
        }
    }
    

    and

    func performUsingSemaphore() {
        let dq1 = DispatchQueue.global(qos: .default)
        let dq2 = DispatchQueue.global(qos: .default)
        let semaphore = DispatchSemaphore(value: 1)
    
        for i in 1...3 {
            dq1.async {
                _ = semaphore.wait(timeout: DispatchTime.distantFuture)
                print("\(#function) DispatchQueue 1: \(i)")
                semaphore.signal()
            }
        }
        for i in 1...3 {
            dq2.async {
                _ = semaphore.wait(timeout: DispatchTime.distantFuture)
                print("\(#function) DispatchQueue 2: \(i)")
                semaphore.signal()
            }
        }
    }
    

提交回复
热议问题