[swift-users] Simultaneous access to global tuple members
Guillaume Lessard
glessard at tffenterprises.com
Tue Aug 8 10:39:05 CDT 2017
> On Aug 8, 2017, at 09:10, Martin R <martinr448 at gmail.com> wrote:
>
> In that example the tuple is a (stored) property of a class, not a global variable. And why does it crash for a global variable, but not for a local variable in a function?
In the case of a local variable in a function, the compiler can statically prove that there is no simultaneous access, and using `swap` is allowed. With a global variable, the compiler can’t statically prove exclusive access.
(it seems silly with your simple example, but the system doesn’t try static enforcement with global variables.)
Here’s another modification which traps at runtime:
***
import Dispatch
func foo() {
var tuple = (1, 2)
let q = DispatchQueue(label: "queue")
q.async { swap(&tuple.0, &tuple.1) }
q.sync {}
print(tuple)
}
foo()
***
Guillaume Lessard
More information about the swift-users
mailing list