Skip to content

mainThread VS mainQueue #3

@DivineDominion

Description

@DivineDominion

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions