Will updating value type variable concurrently or from multiple threads cause crash?

Digging in to find how what conditions can cause crashes in these concurrent cases is laudable. It’s certainly good to understand one’s tools!

But I thought it would be good to point out that Swift currently makes no guarantees about atomicity of its assignment operations. Your questions about the differences between assigning a mere primitive Int vs a complex class makes me think you might be hunting for a deeper answer.

It seems to me like the questions like this often reduce to...“So, what is the smallest operation that Swift can guarantee no other thread can interrupt?” And the answer is that there is none at the moment. Right now you need to bring in your own atomic primitives (like locks, mutexes, or writing C based wrappers around things like C++ atomics so Swift can see them), and using them to protect the things you care about.

That’s why everyone here keeps saying “Don’t worry about why one crashes or the other doesn’t...neither is correct.” Swift does not automatically wrap these assignments in atomic primitives. If it happens to look like it works, you got lucky.

7 Likes