I am trying to write some thread safe methods so I am using:
...
dispatch_queue_t main = dispatch_get_main_queue();
dispatch_sync(main,^{
[self doSomethingInTheForeground];
});
...
But If I am on the main thread that is not necessary, and I can skip all those dispatch calls, so I would like to know what thread I currently am on. How can I know this?
Or, perhaps it does not make difference (in performance) doing it?
Is it ok to do this comparison?
if (dispatch_get_main_queue() == dispatch_get_current_queue()){...}
Check if running on main queue:
if (RunLoop.current == RunLoop.main) {
print("On main queue")
}
Assert if running on main queue:
dispatchPrecondition(condition: .onQueue(.main))
// Code running on main queue
Assert if NOT running on main queue:
dispatchPrecondition(condition: .notOnQueue(.main))
// Code NOT running on main queue
ObjC: Check if running on main queue:
if ([[NSRunLoop currentRunLoop] isEqual: [NSRunLoop mainRunLoop]]) {
NSLog(@"Running on main");
} else {
NSLog(@"Not running on main");
}
Assert if running on main queue:
dispatch_assert_queue(dispatch_get_main_queue());
Assert if NOT running on main queue:
dispatch_assert_queue_not(dispatch_get_main_queue());
NOTE:
mainThread != mainQueue
The main queue always runs on the main thread, but a queue may be running on the main thread without being the main queue. So, don't mix thread and queue tests!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With