Mutex alternatives in swift

前端 未结 3 1292
予麋鹿
予麋鹿 2020-12-29 04:53

I have a shared-memory between multiple threads. I want to prevent these threads access this piece of memory at a same time. (like producer-consumer problem)

<
3条回答
  •  暖寄归人
    2020-12-29 05:03

    There are many solutions for this but I use serial queues for this kind of action:

    let serialQueue = DispatchQueue(label: "queuename")
    serialQueue.sync { 
        //call some code here, I pass here a closure from a method
    }
    

    Edit/Update: Also for semaphores:

    let higherPriority = DispatchQueue.global(qos: .userInitiated)
    let lowerPriority = DispatchQueue.global(qos: .utility)
    
    let semaphore = DispatchSemaphore(value: 1)
    
    func letUsPrint(queue: DispatchQueue, symbol: String) {
        queue.async {
            debugPrint("\(symbol) -- waiting")
            semaphore.wait()  // requesting the resource
    
            for i in 0...10 {
                print(symbol, i)
            }
    
            debugPrint("\(symbol) -- signal")
            semaphore.signal() // releasing the resource
        }
    }
    
    letUsPrint(queue: lowerPriority, symbol: "Low Priority Queue Work")
    letUsPrint(queue: higherPriority, symbol: "High Priority Queue Work")
    
    RunLoop.main.run()
    

提交回复
热议问题