Created
March 15, 2019 08:25
-
-
Save phlippieb/efc836c1cc9ee3807e02eaf62a3358e4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Synched operations will only run one at a time. | |
/// The `operation` method is responsible for calling `complete` to notify the object when it is done. | |
final class SyncedOp { | |
// Use a GCD Semaphore to synchronize flag access. | |
private let semaphore = DispatchSemaphore(value: 1) | |
private var isBusy = false | |
private var isRetriggerQueued = false | |
internal var operation: () -> () = {} | |
internal var retriggerOperation: () -> () = {} | |
internal func run() { | |
semaphore.wait() | |
if isBusy { | |
isRetriggerQueued = true | |
semaphore.signal() | |
} else { | |
isBusy = true | |
isRetriggerQueued = false | |
semaphore.signal() | |
operation() | |
} | |
} | |
internal func complete() { | |
semaphore.wait() | |
isBusy = false | |
if isRetriggerQueued { | |
isRetriggerQueued = false | |
semaphore.signal() | |
retriggerOperation() | |
} else { | |
semaphore.signal() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment