Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What GCD queue, main or not, am I running on?

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()){...}
like image 852
nacho4d Avatar asked Feb 09 '11 08:02

nacho4d


1 Answers

New for iOS: 10.0+ and macOS: 10.12+ (tvOS: 10.0+, watchOS:3.0+).

Swift 4+:

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!

like image 180
Sverrisson Avatar answered Sep 20 '22 09:09

Sverrisson