[swift-evolution] Introducing synthesized locks

Kevin Nattinger swift at nattinger.net
Tue Jun 13 12:30:59 CDT 2017


I'd prefer to see block-scoped synchronization rather than whole-method-only; it gives much more flexibility.

Note that you can use the objc synchronization feature with reference types:

// Or (_ obj:...) if you prefer the label-less objc style)
func synchronized(on obj: AnyObject, do block: () throws -> Void) rethrows {
    objc_sync_enter(obj)
    defer {
        objc_sync_exit(obj)
    }
    try block()
}

// or synchronized(self)
synchronized(on: self) {
    // do something
}
try synchronized(on: self) {
    throw NSError()
}

Not 100% sure this works with bridged reference types (e.g. Array); definitely doesn't work with Int. Use a dummy NSObject() if needed.

That said, I'd love to see a swift-native solution that works with value types (and doesn't rely on the objc runtime).

> On Jun 12, 2017, at 2:10 AM, Erik Aigner via swift-evolution <swift-evolution at swift.org> wrote:
> [...]
> With synchronized attribute (the semaphore/wait/deferred-signal is synthesized by Swift automatically)
> 
> class Obj {
> 
> 	synchronized func method() {
> 		// semaphore is synthesized automatically, do something…
> 	}
> }
> 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170613/bd3bb1c2/attachment.html>


More information about the swift-evolution mailing list