Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex alternatives in swift

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?

like image 801
rick Avatar asked Sep 12 '17 06:09

rick


People also ask

Which is better semaphore or mutex?

If you have number of instances for resource it is better to use Binary semaphore. If you have single instance for resource it is better to use mutex.

What is mutex in Swift?

To refresh the memory, in a multithreaded, program access to a shared resource is organized through a limited region of code, also known as a critical section and a mutex is a program object that prevents simultaneous access to that region of code, i.e., guarantees mutual exclusion.

What is the difference between semaphore and mutex?

A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.

What is semaphore in Swift?

Swift is a multi-threaded language, which means multiple tasks/operations can be executed in parallel, which may or may not be accessing shared resources.


1 Answers

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() 
like image 117
Devanshu Saini Avatar answered Sep 23 '22 21:09

Devanshu Saini