[swift-users] Simultaneous accesses, but modification requires exclusive access

Zhao Xin owenzx at gmail.com
Mon Jul 24 04:38:38 CDT 2017


You can use serial queue.

class Car {

    var helper = Helper()

    lazy private var queue = DispatchQueue(label: "my queue")



    func test() {

        helper.doSomething(f1: f1)

    }



    func f1() {

        queue.async {

            _ = self.helper.v1 //Crash - Simultaneous accesses to <memory
address>, but modification requires exclusive access.

        }

    }

}


Zhao Xin

On Mon, Jul 24, 2017 at 4:22 PM, Quinn "The Eskimo!" via swift-users <
swift-users at swift.org> wrote:

>
> On 24 Jul 2017, at 07:04, somu subscribe via swift-users <
> swift-users at swift.org> wrote:
>
> > - Is there a bug in my code which is being detected in Xcode 9 ?
>
> Yes.  The problem here is that `doSomething(f1:)` is a mutating function,
> so it acts like it takes an `inout` reference to `self.helper`.  That’s one
> mutable reference.  It then calls `Car.f1()`, which tries to get a
> non-mutating reference to exactly the same struct.  This is outlawed in
> Swift 4 as part of the memory ownership effort.
>
> You can read more about the specific change in SE-0176 “Enforce Exclusive
> Access to Memory”.
>
> <https://github.com/apple/swift-evolution/blob/master/
> proposals/0176-enforce-exclusive-access-to-memory.md>
>
> And the general background to this in the “Ownership Manifesto"
>
> <https://github.com/apple/swift/blob/master/docs/OwnershipManifesto.md>
>
> > If so could you please explain and suggest an alternate approach / fix ?
>
> It’s hard to offer concrete suggestions without knowing more about your
> high-level goals.  One option is for `doSomething(f1:)` to pass the `inout`
> reference through to `f1`.  For example:
>
>     mutating func doSomething(f1: (inout Helper) -> ()) {
>         f1(&self)
>     }
>
>     func f1(h: inout Helper) {
>         _ = h.v1  // no crash
>     }
>
> but whether that makes sense in your code is for you to decide.
>
> Share and Enjoy
> --
> Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
> Apple Developer Relations, Developer Technical Support, Core OS/Hardware
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170724/74ced942/attachment.html>


More information about the swift-users mailing list