ios - 快速互斥替代品

标签 ios swift swift3 concurrency mutual-exclusion

我在多个线程之间有一个共享内存。我想防止这些线程同时访问这 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/

相关文章:

ios - 如何将 AVCaptureVideoPreviewLayer 旋转 90 度以在 iOS11 中更正它?

iOS 13 为从 UIImagePickController 中选择的文件添加了 "trim."前缀

ios - 在 Xcode 模拟器中将 View 堆栈压缩到一个 block 中

ios - 从 SKS 文件加载节点时使用的初始化器

ios - App Code arch 已经存在于 fat dylib 中

ios - 将 View 数加载到 UIScrollView 时由于内存错误而终止

iphone - UIAlertView 渲染错误

ios - Swift UIButton 操作和 GestureRecognizer

swift - 在 Firebase 中查询数组

Swift - 制作结构数组