@Atomic property wrapper for standard library?

I think an atomic property wrapper is almost never what you want.

Leaving aside the difficulty of performing the synchronisation using Swift’s accessor model which generalized accessors solves, the bigger problem is that you usually want to hoist the scope of your synchronization. It’s rare that you want to synchronize one property; you usually want to synchronize multiple, or nested ones. You also often want to store that property in a local variable which now immediately loses synchronization. In general this property wrapper replaces data races with logic errors, which may not be the outcome you want.

It is in general better to design your way out of data races rather than slap a property wrapper on your properties until the crashes go away. You can find many threading issues using thread sanitizer, so these shouldn’t have to catch you by surprise.

You should make clear decisions about what thread or mutex owns what data, and then enforce those restrictions. When you don’t know what context you’re in, assume you’re in the wrong one and reacquire the owned context. Assume any callback may be invoked on arbitrary threads unless explicitly documented otherwise. All of these lead to better outcomes than synchronization decorators, in my view.

33 Likes