Buffer icon indicating copy to clipboard operation
Buffer copied to clipboard

mainThread VS mainQueue

Open DivineDominion opened this issue 7 years ago • 5 comments

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
}

DivineDominion avatar Sep 01 '16 12:09 DivineDominion

Thank you for the tip! Will update the threading code to improve the main thread check 👍

alexdrone avatar Sep 02 '16 09:09 alexdrone

The use of get_specific is highly discouraged by Apple

grgcombs avatar Mar 09 '17 19:03 grgcombs

@grgcombs can you point at something to read up on? For example if it's causing problems, which ones?

DivineDominion avatar Mar 11 '17 10:03 DivineDominion

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 avatar Mar 11 '17 20:03 grgcombs

@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.

richardtop avatar Jan 23 '18 14:01 richardtop