我在多个线程之间有一个共享内存。我想防止这些线程同时访问这 block 内存。 (比如生产者-消费者问题)
问题:
一个线程向队列中添加元素,另一个线程读取这些元素并删除它们。他们不应同时访问队列。
这个问题的一个解决方案是使用 Mutex。
正如我所发现的,Swift 中没有 Mutex。 Swift 中有其他替代方案吗?
最佳答案
对此有很多解决方案,但我对这种操作使用串行队列:
let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync {
//call some code here, I pass here a closure from a method
}
编辑/更新:也适用于信号量:
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()
关于ios - 快速互斥替代品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46169519/