Mutex alternatives in swift

rick picture rick · Sep 12, 2017 · Viewed 12.4k times · Source

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)

Problem:

A thread add elements to a queue and another thread reads these elements and delete them. They shouldn't access the queue simultaneously.

One solution to this problem is to use Mutex.

As I found, there is no Mutex in Swift. Is there any alternatives in Swift?

Answer

Devanshu Saini picture Devanshu Saini · Sep 12, 2017

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()