Skip to content

Instantly share code, notes, and snippets.

@phlippieb
Created March 15, 2019 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phlippieb/efc836c1cc9ee3807e02eaf62a3358e4 to your computer and use it in GitHub Desktop.
Save phlippieb/efc836c1cc9ee3807e02eaf62a3358e4 to your computer and use it in GitHub Desktop.
/// 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