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?
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.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With