Skip to content

Instantly share code, notes, and snippets.

@mwrites
Last active October 13, 2017 10:13
Show Gist options
  • Save mwrites/525f257aa148f91bf9109b230bb42710 to your computer and use it in GitHub Desktop.
Save mwrites/525f257aa148f91bf9109b230bb42710 to your computer and use it in GitHub Desktop.
MainQueue vs MainThread
@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