absl::MutexLock l(&mutex_);
// Critical section.
The idea that you have to write a "waiting queue" every time you need to guard shared state in Swift is mind boggling. Surely not! absl::MutexLock l(&mutex_);
// Critical section.
The idea that you have to write a "waiting queue" every time you need to guard shared state in Swift is mind boggling. Surely not!The queues provided by Apples GCD are an abstraction above threads and mutexes. The equivalent to your critical section example is:
let dispatchQueue = DispatchQueue(label: "com.mycompany.myComponent") // Initialize queue, just as you would with the mutex, label will show in debugger
dispatchQueue.sync { // Critical section }
There are several wins here. One is that gcd controls thread creation as needed. But the bigger win is when you have a longer running critical section and mustn't block the calling UI (main) queue. Then you can simply do an async dispatch on the queue and callback to the UI queue on completion. GCD will also introduce the necessary memory barriers for passing data between the queues.
serialQueue.async { // Critical section } is GCD's way of doing the same with the added benefit that the calling code does not have to wait.
Problems in the parent code could be solved by using a mutex instead of GCD in this case. The code _has_ to wait for the access token to be loaded and not blocking does not make sense here unless you also introduce some kind of Promises.
Also, GCD has DispatchSemaphore that is a Semaphore. Mutexes is a particular case of semaphores.
2. Creating dispatch queues is trivial and most surely you already created one for other tasks.
3. You miss the context of this article.
Try doing that on the main thread of a simple command line utility and nothing happens.
Try locking the main thread of a GUI Application, and you did a beginners mistake, your App will lock.
GUI API calls must be done on the main thread and that's where our View Controllers run in.