Buffer
Buffer copied to clipboard
mainThread VS mainQueue
There are quite a few checks like NSThread.isMainThread()
in the code. Maybe this should be changed to checking for the main queue instead?
Here's sample code to check for the queue instead, based on http://blog.benjamin-encz.de/post/main-queue-vs-main-thread/, where the difference is explained, too:
private let mainQueueKey = UnsafeMutablePointer<Void>.alloc(1)
private let mainQueueValue = UnsafeMutablePointer<Void>.alloc(1)
// Associate a key-value pair with the main queue
dispatch_queue_set_specific(
dispatch_get_main_queue(),
mainQueueKey,
mainQueueValue,
nil
)
func dispatch_ensure_main_queue(block: dispatch_block_t) {
// Check for presence of key-value pair on current queue
if (dispatch_get_specific(mainQueueKey) == mainQueueValue) {
// if we found right value for key, execute immediately
print("main queue")
block()
} else {
// otherwise dispatch on main queue now
// /!\ Use dispatch_sync cautiously
// it can cause deadlocks!
dispatch_sync(dispatch_get_main_queue()) {
print("not main queue")
block()
}
}
return image
}
Thank you for the tip! Will update the threading code to improve the main thread check 👍
The use of get_specific is highly discouraged by Apple
@grgcombs can you point at something to read up on? For example if it's causing problems, which ones?
Wow -- could be that I totally fabricated that idea. I cannot find the tech note or release notes that talk about this. Will keep looking, but for now just assume I was pranking you.
@grgcombs It's written here: https://developer.apple.com/documentation/dispatch/1453125-dispatch_get_specific
The key associated with the dispatch queue on which the current block is executing. Keys are only compared as pointers and never dereferenced. Passing a string constant directly is not recommended.
In the example mentioned above this function is used correctly: it's being invoked with a pointer.