I've searched the Swift book, but can't find the Swift version of @synchronized. How do I do mutual exclusion in Swift?
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
Swift 3
This code has the re-entry ability and can work with Asynchronous function calls. In this code, after someAsyncFunc() is called, another function closure on the serial queue will process but be blocked by semaphore.wait() until signal() is called. internalQueue.sync shouldn't be used as it will block the main thread if I'm not mistaken.
objc_sync_enter/objc_sync_exit isn't a good idea without error handling.
Use GCD. It is a little more verbose than
@synchronized
, but works perfectly well as a replacement:Why make it difficult and hassle with locks? Use Dispatch Barriers.
A dispatch barrier creates a synchronization point within a concurrent queue.
While it’s running, no other block on the queue is allowed to run, even if it’s concurrent and other cores are available.
If that sounds like an exclusive (write) lock, it is. Non-barrier blocks can be thought of as shared (read) locks.
As long as all access to the resource is performed through the queue, barriers provide very cheap synchronization.
You can sandwich statements between
objc_sync_enter(obj: AnyObject?)
andobjc_sync_exit(obj: AnyObject?)
. The @synchronized keyword is using those methods under the covers. i.e.Use NSLock in Swift4:
To add return functionalty, you could do this:
Subsequently, you can call it using: