Skip to content

Instantly share code, notes, and snippets.

@yakushevichsv
Created August 29, 2021 16:14
Show Gist options
  • Save yakushevichsv/56d0e305eaa7e738d526ce38fe7d72f2 to your computer and use it in GitHub Desktop.
Save yakushevichsv/56d0e305eaa7e738d526ce38fe7d72f2 to your computer and use it in GitHub Desktop.
Test code for checking DispatchQueue.getSpecific method
final class Test {
private let queue: DispatchQueue
private let queueKey : DispatchSpecificKey<Int>
private let queueKeyValue: Int
init() {
let queueKey = DispatchSpecificKey<Int>()
let queueKeyValue = Int(arc4random())
self.queueKey = queueKey
self.queueKeyValue = queueKeyValue
queue = .init(label: "custom.queue") //.global(qos: .background)
queue.setSpecific(key: queueKey, value: queueKeyValue)
}
func testQueue() {
func check(inQueue flag: Bool) {
debugPrint(#function + " in queue \(flag)")
guard checkIfInQueue() == flag else {
assertionFailure("Failed in queue \(flag)")
return
}
debugPrint("Called flag \(flag)")
}
DispatchQueue.main.async(execute: { check(inQueue: false) })
runOnQueue { check(inQueue: true) }
//Thread.isMainThread
}
private func checkIfInQueue() -> Bool {
DispatchQueue.getSpecific(key: queueKey) == queueKeyValue
}
private func runOnQueue(_ block: @escaping () -> Void,
dispatchSynch: Bool = false) {
let tempBlock: ( Bool ) -> Void = { [weak self] smartSync in
if smartSync {
block()
} else if dispatchSynch {
self?.queue.sync(execute: block)
} else {
self?.queue.async(execute: block)
}
}
tempBlock(checkIfInQueue())
}
}
let x = Test()
x.testQueue()
/*
void *xmppQueueTag;
- (void) init {
// ......
xmppQueueTag = &xmppQueueTag;
xmppQueue = dispatch_queue_create("xmpp", DISPATCH_QUEUE_SERIAL);
dispatch_queue_set_specific(xmppQueue, xmppQueueTag, xmppQueueTag, NULL);
}
- (void) run {
// ......
if (dispatch_get_specific(xmppQueueTag))
block();
else
dispatch_sync(xmppQueue, block);
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment