And what I was perplexed by is what it means by instantaneous access, particularly in the case of multithreaded code.
It mentions “ An access is instantaneous if it’s not possible for other code to run after that access starts but before it ends. By their nature, two instantaneous accesses can’t happen at the same time. Most memory access is instantaneous.”
I had assumed that no code can truly be instantaneous like that because of multithreading. I can schedule two threads to access the same variable. And since they run concurrently to each other, it means they can access the same location in memory at the exact same time.
Is the documentation saying otherwise, that some code is in fact truly instantaneous, or is this a case of bad document where it forgets to discuss memory conflicts in the case of concurrently running code?
(Asides, why doesnt a memory safety article having anything about race conditions, which is probably a much more common scenario where theres memory “conflicts”? Why this article focus on these cases involving in out parameters?)
My recollection (admittedly it's been a bit, it's possible I'm misremembering) is that this is a very "language formalism" bit of reasoning: a Swift program that contains data races is not valid, and the language does not specify the behavior of invalid code. Whether this is a useful way to phrase it for people other than compiler engineers is less clear to me, might be worth a bug report.
Swift Concurrency does attempt to prevent such invalid programs from compiling, but it came much later in Swift's history; perhaps it would make sense to update this part of the documentation now that the formal design of the language does include concurrency.
i agree with David that there's an underlying assumption in the docs that the code is already free of data races.
the evolution document for SE-0176 ('Enforce Exclusive Access to Memory') makes this somewhat more clear than the documentation. in the 'Instantaneous and non-instantaneous accesses' section it states:
Because arbitrary other code can't run during an instantaneous access, it's never possible for two instantaneous accesses to overlap each other (without introducing concurrency, which we'll talk about later).
and then later in the 'Concurrency' section, there's this:
Swift has always considered read/write and write/write races on the same variable to be undefined behavior. It is the programmer's responsibility to avoid such races in their code by using appropriate thread-safe programming techniques.
it seems to me that the book documentation could be clearer on this point.