When to use Semaphore instead of Dispatch Group?

前端 未结 4 1997
无人及你
无人及你 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 07:59

    One typical semaphore use case is a function that can be called simultaneously from different threads and uses a resource that should not be called from multiple threads at the same time:

    func myFunction() {
        semaphore.wait()
        // access the shared resource
        semaphore.signal()
    }
    

    In this case you will be able to call myFunction from different threads but they won't be able to reach the locked resource simultaneously. One of them will have to wait until the second one finishes its work.

    A semaphore keeps a count, therefore you can actually allow for a given number of threads to enter your function at the same time.

    Typical shared resource is the output to a file.

    A semaphore is not the only way to solve such problems. You can also add the code to a serial queue, for example.

    Semaphores are low level primitives and most likely they are used a lot under the hood in GCD.

    Another typical example is the producer-consumer problem, where the signal and wait calls are actually part of two different functions. One which produces data and one which consumes them.

提交回复
热议问题