3 ms·
This seems craaaazy complicated. In C++, I'm only familiar with the abseil libraries for thread safety, but the way to make sure multiple threads don't access s
by asdfasgasdgasdg 8y ago
This seems craaaazy complicated. In C++, I'm only familiar with the abseil libraries for thread safety, but the way to make sure multiple threads don't access shared state is:
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!
- jchb 8y agoThe waiting queue mechanism in the article is related to the specific requirements of that auth network request rather than Swift in general. 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.
- coldcode 8y agoI find the lack of language level locking a benefit in Swift, using GCD is really easy now that the syntax is much more polished. I have yet to run into a race condition. When I worked (years ago) on a 3D game engine in C++ we actually removed most of the multi-threading because it was too hard to reason what it was doing and avoid threading errors and race conditions.
- sovande 8y agoSwift has easy access to pthread mutex and you can do that. 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.
- bunnycorn 8y agoThis. Also, GCD has DispatchSemaphore that is a Semaphore. Mutexes is a particular case of semaphores.
- bunnycorn 8y ago1. You don't, as said before. 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.