Swift Atomics
swift.org
swift.org
That said, I’m not a systems programmer, and basic threads, like those provided by the standard “blunt instrument” approach of standard Swift, will pretty much always give me what I need.
Using threads -especially low-level threads- can lead to a real education in debugging. I only use them when necessary.
FWIW, this is among the first of quite a few concurrency improvements coming to Swift in the near future. Swift 6 is expected to include a real concurrency model, likely based on some combination of async/await and an actor model.
The devs have been actively implementing a prototype [0], and the core team is expected to release a design document/proposal soon [1] [2].
[0]: https://github.com/apple/swift/pulls?q=concurrency [1]: https://forums.swift.org/t/rethinking-async/37984/30 [2]: https://forums.swift.org/t/rethinking-async/37984/51
Oh yeah it can. I'm still scarred by an error that took me a month to solve: I was self-teaching pthreads and kept getting an access violation with a stack trace starting at 0x0.
Later I saw some suspicious compiler bug fixes around compare and swap, and I still wonder if that was maybe it.
Me I'd rather roll my own cryto than try and write my own lock free data structure.
https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-20... https://channel9.msdn.com/Shows/Going+Deep/Cpp-and-Beyond-20...
He goes into the details of ARM vs Intel etc in the middle of part 2, but really part 1 is well worth a watch.
Which is very nice of them.
I still think a logic bug or compiler bug was at fault though.
Atomic access can use relaxed memory ordering, meaning that values don't actually change immediately for all threads. There are subtle rules about what changes the hardware and the optimizer can delay and reorder. It's like playing chess with threads.
There's also a common pitfall that x86 hardware has more consistent and forgiving behavior than the spec for atomic operations. Broken atomic code may appear to work fine on x86, but fall apart on ARM.
That's why the standard advice on iOS and macOS was to mark properties as explicitly `nonatomic` – because it was almost never the right tool for the job.
Thus it's likely that a developer using atomics still makes mistakes, and yet they get a false sence of safety.
But that's all you get. And the catch is that there's usually more you need to do to guarantee thread safety for a particular operation.
For example, `@property (atomic) NSMutableArray *array;` has no guarantees about appending or removing the array's _contents_.
For another example `@property (atomic) NSUInteger count;` is a mildly subtle trap, because a statement like `self.count += 1;` is _not atomic_. It's an atomic read, an increment, and an atomic write. You need another synchronization mechanism to make the whole update threadsafe.
Those books were corny as hell but the fact that the hero saved the day with his wits made an impression on me as a young lad.