Skip to content

Instantly share code, notes, and snippets.

@ricardopereira
Forked from khanlou/SafeSyncQueue.swift
Created July 13, 2019 07:27
Show Gist options
  • Save ricardopereira/6ace4becfd0d07a4c5d6a3da936ae5eb to your computer and use it in GitHub Desktop.
Save ricardopereira/6ace4becfd0d07a4c5d6a3da936ae5eb to your computer and use it in GitHub Desktop.
import Foundation
final class SafeSyncQueue {
struct QueueIdentity {
let label: String
}
let queue: DispatchQueue
fileprivate let queueKey: DispatchSpecificKey<QueueIdentity>
init(label: String) {
self.queue = DispatchQueue(label: "com.khanlou.\(label).SafeSyncQueue")
self.queueKey = DispatchSpecificKey<QueueIdentity>()
self.queue.setSpecific(key: queueKey, value: QueueIdentity(label: queue.label))
}
fileprivate var currentQueueIdentity: QueueIdentity? {
return DispatchQueue.getSpecific(key: queueKey)
}
func sync(execute: ()->()) {
if currentQueueIdentity?.label == queue.label {
execute()
} else {
queue.sync(execute: execute)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment