Last active
October 13, 2017 10:13
-
-
Save mwrites/525f257aa148f91bf9109b230bb42710 to your computer and use it in GitHub Desktop.
MainQueue vs MainThread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@UIApplicationMain | |
class AppDelegate: UIResponder, UIApplicationDelegate { | |
var window: UIWindow? | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { | |
let k = DispatchSpecificKey<String>() | |
DispatchQueue.main.setSpecific(key: k, value: "MainQ") | |
if Thread.isMainThread { | |
print("MainThread") | |
} else { | |
print("Not MainThread") | |
} | |
if DispatchQueue.getSpecific(key: k) != nil { | |
print("MainQ") | |
} else { | |
print("Not MainQ") | |
} | |
//prints MainThread, MainQ | |
//we are executing on MainThread but not on MainQueue | |
let newQ = DispatchQueue(label: "NewQ") | |
let newQk = DispatchSpecificKey<String>() | |
newQ.setSpecific(key: newQk, value: "NewQ") | |
newQ.sync { | |
if Thread.isMainThread { | |
print("MainThread") | |
} else { | |
print("Not MainThread") | |
} | |
if DispatchQueue.getSpecific(key: k) != nil { | |
print("MainQ") | |
} else { | |
print("Not MainQ") | |
} | |
if DispatchQueue.getSpecific(key: k) != nil { | |
print("MainQ") | |
} else { | |
print("Not MainQ") | |
} | |
if DispatchQueue.getSpecific(key: newQk) != nil { | |
print("NewQ") | |
} else { | |
print("Not NewQ") | |
} | |
//prints MainThread, Not MainQ, NewQ | |
} | |
DispatchQueue.global().async { | |
if Thread.isMainThread { | |
print("MainThread") | |
} else { | |
print("Not MainThread") | |
} | |
if DispatchQueue.getSpecific(key: k) != nil { | |
print("MainQ") | |
} else { | |
print("Not MainQ") | |
} | |
//prints Not MainThread, Not MainQ | |
DispatchQueue.main.sync { | |
if Thread.isMainThread { | |
print("MainThread") | |
} else { | |
print("Not MainThread") | |
} | |
if DispatchQueue.getSpecific(key: k) != nil { | |
print("MainQ") | |
} else { | |
print("Not MainQ") | |
} | |
//prints MainThread, MainQ | |
} | |
} | |
return true | |
} | |
} | |
/* | |
- http://blog.benjamin-encz.de/post/main-queue-vs-main-thread/ | |
- http://blog.krzyzanowskim.com/2016/06/03/queues-are-not-bound-to-any-specific-thread/ | |
- Threads are reused. Queues reuse threads in general. If so, the Main thread can be reused by another queue (for example by concurrent queue) when Main thread is idle. | |
- Main Queue IS bound to Main Thread. | |
- Main Thread IS NOT bound to Main Queue. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment