Alternatives to Mutex in Fast

I have shared memory between multiple threads. I want these threads to not pay attention to this part of the memory at the same time. (e.g. producer-consumer problem)

Problem

A thread adds items to the queue, and another thread reads these items and deletes them. They should not be accessing the queue at the same time.

One solution to this problem is to use Mutex.

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

+14
source share
3 answers

( ), . , , , -, . Apples doc, " " , , (= ), , ​​ . , (, , ). , .

, . , , . , "". , , , , , , . , .

+3

, :

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

Thanks to the beshio comment , you can use the semaphore as follows:

let semaphore = DispatchSemaphore(value: 1)

use wait before using the resource:

semaphore.wait()
// use the resource

and after using release:

semaphore.signal()

Do it in every thread.

+6
source

All Articles