Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Main Queue / Current Queue & Main Thread / Background Thread in this case?

I'm executing the following method :

MotionHandler.m

-(void)startAccelerationUpdates
{
    [motionManagerstartDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]withHandler:^(CMDeviceMotion *motion, NSError *error){.....}
}

on a background thread, as follows:

[currentMotionHandler performSelectorInBackground:@selector(startAccelerationUpdates) withObject:nil];

But the above method uses the main Queue (which is on the main thread) to perform the necessary updates even though I'm calling it on a background thread.. So are acceleration updates being performed on a background thread or on the main thread, I'm confused..?

What's even more interesting is that when I call the above method on background thread again, but this time using the current Queue, I get no updates. Could someone please explain the difference between running something on :

 1. a background thread but on the main queue

 2. a background thread but on the current queue 

 3. the main thread but on the main queue  

 4. the main thread but on the current queue

in the current implementation? Thank you!

like image 852
Norton Commander Avatar asked Dec 11 '25 17:12

Norton Commander


1 Answers

I'll give it a shot. First, without being told by the NSOperationQueue class reference, we could not infer anything about what thread the 'mainQueue' would run on. Reading it we see that in fact that queue runs its operations on the mainThread, the one the UI uses, so you can update the UI in operations posted to that queue. Although it doesn't say it, these operations must be serial, due to them being executed by the runLoop (its possible they can get preempted too, not 100% sure of that).

The purpose for currentQueue is so that running operations can determine the queue they are on, and so they can potentially queue new operations on that queue.

  1. a background thread but on the main queue

Not possible - the NSOperation's mainQueue is always associated with the mainThread.

  1. a background thread but on the current queue

When you create a NSOperationQueue, and add NSOperations to it, those get run on background threads managed by the queue. Any given operation can query what thread its on, and that thread won't change while it runs. That said, a second operation on that queue may get run on a different thread.

  1. the main thread but on the main queue

See 1)

  1. the main thread but on the current queue

If you queue an operation to the mainQueue (which we know is always on the mainThread), and you ask for the currentQueue, it will return the mainQueue:

[NSOperationQueue currentQueue] == [NSOperationQueue mainQueue];
like image 81
David H Avatar answered Dec 14 '25 06:12

David H