when to use dispatch_get_main_queue - ios

I have learnt one global rule in iOS -> never to block main thread.
However, several time I run into open source code snippets where this rule is violated.
Two such examples are follows :
The following function is taken from
https://github.com/piwik/piwik-sdk-ios/blob/master/PiwikTracker/PiwikTracker.m
- (void)startDispatchTimer {
// Run on main thread run loop
__weak typeof(self)weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf stopDispatchTimer];
// If dispatch interval is 0) {
// Run on timer
weakSelf.dispatchTimer = [NSTimer scheduledTimerWithTimeInterval:weakSelf.dispatchInterval
target:weakSelf
selector:#selector(dispatch:)
userInfo:nil
repeats:NO];
NSLog(#"Dispatch timer started with interval %f", weakSelf.dispatchInterval);
}
});
}
In the above code I have been trying to understand why is main thread required for timer object. Something like this is not UI related and still done on main thread.
Another example of this is in a famous networking library MKNetworkKit .
Where the following code is in start method of NSOperation.
https://github.com/MugunthKumar/MKNetworkKit/blob/master/MKNetworkKit/MKNetworkOperation.m
dispatch_async(dispatch_get_main_queue(), ^{
self.connection = [[NSURLConnection alloc] initWithRequest:self.request
delegate:self
startImmediately:NO];
[self.connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[self.connection start];
});
So my questions is why do people use main thread for doing no UI related operations and what benefit does it give. It may not freeze your app if you are not holding on to it but why take a chance.

Both examples are using NSRunLoop methods directly or indirectly. In those cases, you should call the methods from the thread which executes the target NSRunLoop. Thus you need dispatch_get_main_queue().
Take a look at the apple document about NSRunLoop https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/classes/nsrunloop_class/reference/reference.html
Warning: The NSRunLoop class is generally not considered to be thread-safe and its methods should only be called within the context of the current thread. You should never try to call the methods of an NSRunLoop object running in a different thread, as doing so might cause unexpected results.
By the way, NSRunLoop seems using CFRunLoop in Core Foundation, and Core Foundation was released under an open source license from Apple.
http://opensource.apple.com/source/CF/CF-855.17/CFRunLoop.c
It seems CFRunLoop is thread-safe (we can see a lot of __CFRunLoopLock and __CFRunLoopUnlock combination). But you would better obey the document anyway :)

Related

DispatchQueue bound to exact Thread

im developing an app, which uses some framework to draw 3D staff via openGL. This framework requires me to call draw() method from exact the same Thread.
So i created a serial DispatchQueue and started CADisplayLink in it, calling draw() at 60FPS. There are few other methods that i have to call from this exact thread, like start() and stop(). This makes queues perfect solution to me.
As you may know DispathQueue does not guaranteed to execute every task on the same thread. Which is quite stressful for me, as it may break my app.
I don't really like the idea to create NSThread and implement my own queue on it.
Are there any way to bind DispatchQueue to exact Thread? Maybe NSOperationQueue can be bound?
As Apple Documentation says:
When it comes to adding concurrency to an application, dispatch queues provide several advantages over threads. The most direct advantage is the simplicity of the work-queue programming model. With threads, you have to write code both for the work you want to perform and for the creation and management of the threads themselves. Dispatch queues let you focus on the work you actually want to perform without having to worry about the thread creation and management. Instead, the system handles all of the thread creation and management for you. The advantage is that the system is able to manage threads much more efficiently than any single application ever could. The system can scale the number of threads dynamically based on the available resources and current system conditions. In addition, the system is usually able to start running your task more quickly than you could if you created the thread yourself.
In simple words, you either work with dispatch queues, simply creating them and sending work to them, OR you work with NSThreads and NSRunLoops, creating them, setting them up, sending work to them, and possibly stopping them.
In detail:
NSThread / NSRunLoop
Creation:
self.thread = [[NSThread alloc] initWithTarget:self selector:#selector(threadMainRoutine) object:nil];
[self.thread start];
Start / management:
- (void)threadMainRoutine
{
// Set the runLoop variable, to signal this thread is alive
self.runLoop = [NSRunLoop currentRunLoop];
// Add a fake Mach port to the Run Loop, to avoid useless iterations of the main loop when the
// thread is just started (at this time there are no events added to the run loop, so it will
// exit immediately from its run() method)
[self.runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
//--- Thread main loop
while (thread_KeepRunning)
{
// Run the run loop. This function returns immediately if the RunLoop has nothing to do.
// NOTE: THIS STATEMENT:
// [self.runLoop run];
// DOES NOT WORK, although it is equivalent to CFRunLoopRun();
CFRunLoopRun();
}
// Unset the runLoop variable, to signal this thread is about to exit
self.runLoop = nil;
}
Adding work to be performed on it:
[self performSelector:#selector(mySelector:) onThread:myThread withObject:myObject waitUntilDone:YES];
Shutdown:
- (void)stop
{
if (self.thread) {
while (self.thread.isExecuting) {
thread_KeepRunning = NO;
CFRunLoopStop([self.runLoop getCFRunLoop]);
[NSThread sleepForTimeInterval:0.1f];
}
}
self.runLoop = nil;
self.thread = nil;
}
Dispatch Queue
Creation:
dispatch_queue_t myQueue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_SERIAL);
Start:
dispatch_resume(myQueue);
Adding work to be performed on it:
dispatch_async(myQueue, (void)^ {
// put the work into this block
});
Shutdown:
dispatch_suspend(myQueue);
myQueue = nil;
In addition, Apple Documentation says that
Because Grand Central Dispatch manages the relationship between the tasks you provide and the threads on which those tasks run, you should generally avoid calling POSIX thread routines from your task code. If you do need to call them for some reason, you should be very careful about which routines you call
So: if you use dispatch queues, don't mess with threads.

Stop a NSRunLoop in global queue

I have just created a background task with a timer using NSRunLoop and NSTimer in my ViewController:
- (void)runBackgroundTask: (int) time{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:#selector(startTrackingBg) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
}
To call a function that will verify token validity, etc. Is it possible to end this loop from inside the function? For instance:
-(void)startTrackingBg
{
if(TOKEN IS NOT VALID)
{
STOP_THREAD;
dispatch_sync(dispatch_get_main_queue(), ^{
[self alertStatus:#"Session Lost!" :#"Error!"];
[self popToLogin];
});
}
}
A couple of thoughts:
If you look at the documentation for run, they show a pattern that solves your problem:
If no input sources or timers are attached to the run loop, this method exits immediately; otherwise, it runs the receiver in the NSDefaultRunLoopMode by repeatedly invoking runMode:beforeDate:. In other words, this method effectively begins an infinite loop that processes data from the run loop’s input sources and timers.
Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. OS X can install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.
If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop. A simple example would be:
BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
where shouldKeepRunning is set to NO somewhere else in the program.
Having said that, if I were going to start another thread, I wouldn't use up one of the global worker threads, but rather I'd just instantiate my own NSThread.
More critically, depending upon what you're trying to do in this other thread, there are generally much better other patterns than establishing your own run loop.
For example, if I wanted to have timer run something in another queue, I'd use a dispatch timer instead:
#property (nonatomic, strong) dispatch_source_t timer;
and then instantiate and start dispatch timer source to run on your designated GCD queue:
dispatch_queue_t queue = dispatch_queue_create("com.domain.app.polltimer", 0);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), kPollFrequencySeconds * NSEC_PER_SEC, 1ull * NSEC_PER_SEC);
dispatch_source_set_event_handler(self.timer, ^{
<#code to be run upon timer event#>
});
dispatch_resume(self.timer);
Or, if you want to use NSTimer, just schedule that on the main runloop, and have the method it calls dispatch the time consuming task to the background queue at that time. But, either way, I'd avoid adding the overhead of a second run loop.
Having shown you better ways to use timers in background threads, now that you describe the intent (polling a server) I'd actually recommend against using timer at all. Timers are useful when you want some action to be initiated at some regular interval. But in this case, you probably want to initiate the next server request after a certain amount of time after the previous request finished. So, in the completion block of the previous request, you might do something like:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 20.0 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
<#code to initiate next request#>
});
Also, I'd personally want to make sure there was a very compelling reason to polling your server. Polling always seems so intuitively appealing and logical, but it is an extravagant use of the user's battery, CPU and data plan. And in those cases where you need the client to respond to server changes quickly, there are often better architectures (sockets, push notifications, etc.).
You do a dispatch async and inside you add a timer to the runloop to run a method periodically? You should add threads to make sure that you use all systems of parallelism at once. ;-)
Seriously: Use dispatch_after() and decide inside the block if you want to do it again.

When should I apply Runloop to my program and why?

My requirement is that I want to call an API to ask for some new information from my server every 6 seconds,so I wrote my code as below:
MyBackgroundThread(){
while(self.isStop){
[self callMyAPI];
[NSThread sleepfortimeinterval : 6 ];
}
}
But I find out today that there is a way provided by Foundation library to write a run loop. So I can rewrite my code as below:
MyBackgroundThread(){
NSTimer *timer = [NSTimer timerWithTimeInterval:6 target:self selector:#selector(callMyAPI) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[timer release];
while (! self.isCancelled) {
BOOL ret = [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
}
However, I don't know if these is a better way to do my job then my original one? If it is, why? and how can I test the difference in efficiency(or other property?) between this two ways?
Thanks!
I think it's generally unnecessary to create new run loop for timer. I'd suggest one of two approaches:
Schedule NSTimer on main run loop, but have the called method then dispatch the request to background queue.
Create dispatch timer scheduled to run on designated background dispatch queue. To do that, create dispatch timer property:
#property (nonatomic, strong) dispatch_source_t timer;
and then instantiate and start dispatch timer source to run on your designated GCD queue:
dispatch_queue_t queue = dispatch_queue_create("com.domain.app.polltimer", 0);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), kPollFrequencySeconds * NSEC_PER_SEC, 1ull * NSEC_PER_SEC);
dispatch_source_set_event_handler(self.timer, ^{
<#code to be run upon timer event#>
});
dispatch_resume(self.timer);
There are times that creating a new run loop is useful, but it seems unnecessary in this simple scenario.
Having said that, it probably doesn't make sense to use a timer for initiating a network every six seconds. Instead, you probably want to start the next request six seconds after the prior one finishes. For a variety of reasons, your server might not be able to respond within six seconds, and you don't want concurrent requests to build up in these scenarios (which can happen if your requests run asynchronously).
So, I'd be inclined that the completion block of callMyAPI to do something as simple as:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(6.0 * NSEC_PER_SEC)), queue, ^{
<#code to issue next request#>
});
This obviates the need for timers (and custom run loops) entirely.
Finally, if you really need to detect system changes with that frequency, it might suggest a very different server architecture. For example, if you're polling every six seconds to see if something changed on the server, you might consider a sockets-based implementation or use push notifications. In both of those approaches, the server will tell the client apps when the significant event takes place, rather than the app behaving like Bart Simpson in the back seat of the car, constantly asking "are we there yet?"
The appropriate architecture is probably a function of with what frequency the server data is likely to be changing and what the client app requirements are.

NSOperation and NSURLConnection

I have an operation "A" that use an async NSURLConnection to retrieve a list of IDs from a web service. When the response is received, the operation loop over these IDs and create an operation "B" for each ID and add them to the queue.
When I started testing with a maxConcurrentOperationCount to 1, I could not execute more than the A operation. So it seems that "B" operations added to the queue are still waiting for "A" completion.
The "executing" and "finished" properties are updated correctly and the KVO notification on "isFinished" is working as expected, but the queue still contains 2 operations, the "A" operation is never removed.
I tried to changed the code which was scheduling the connection in the NSRunLoop with a port, by a "performSelectorOnMainThread: #selector(start)", and it solved this problem, but It creates another one. When operations "B" are executed, depending on the server response they can start other non-concurrent operations "C" by calling their "start" method and not by adding them to the queue, and in this case I need that "B" does not finish until "C" has finished (this is why I'm using "start" and not adding "C" to the queue), and I do not want to execute "C" on the main thread which is what is happening when I use "performSelectorOnMainThread".
If anybody can help me to fix my problem with the runloop code, I tried to look at AFNetworking and other libraries but I don't see what I'm doing wrong.
- (void)send
{
serverConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self startImmediately: NO];
port = [NSPort port];
runLoop = [NSRunLoop currentRunLoop];
[runLoop addPort: port forMode: NSDefaultRunLoopMode];
[serverConnection scheduleInRunLoop: runLoop forMode: NSDefaultRunLoopMode];
[serverConnection start];
[runLoop run];
}
- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)theError
{
[runLoop removePort: port forMode: NSRunLoopCommonModes];
// code handling error
}
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
{
[runLoop removePort: port forMode: NSRunLoopCommonModes];
// code processing response
// If this is executed on main thread, non-concurrent operations created and started from the response processing code,
// will be executed on main thread, instead of using the thread that was dedicated to this operation.
}
According to the documentation for the NSRunLoop method run:
Manually removing all known input sources and timers from the run loop is not a guarantee that the run loop will exit. OS X can install and remove additional input sources as needed to process requests targeted at the receiver’s thread. Those sources could therefore prevent the run loop from exiting.
If you want the run loop to terminate, you shouldn't use this method. Instead, use one of the other run methods and also check other arbitrary conditions of your own, in a loop. A simple example would be:
BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
where shouldKeepRunning is set to NO somewhere else in the program.
Obviously, rather than using shouldKeepRunning, you might use ![self isFinished] instead, but it illustrates the point.
If you're going to enable multiple concurrent operations (and for the sake of efficiently running all of your B requests, you should seriously consider this), you might want to take a look at what AFNetworking did, which was (a) create a single dedicated thread for networking requests and start the run loop there, (b) schedule all network requests on this run loop; and (c) make the operations concurrent (e.g. isConcurrent returns YES).

how to run code in the UI thread calling it from the others ones

In Android there are several ways to run some code in the main thread from others ones:
1. Activity.runOnUiThread(Runnable r)
2. new Handler.post(Runnable r);
3. View.post
What are the analogues in iOS?
dispatch_async(dispatch_get_main_queue(), ^{
});
Something else?
Thanks in advance.
The preferred way nowadays is using GCD, with the code you quoted in your question:
dispatch_async(dispatch_get_main_queue(), ^{
// Your code to run on the main queue/thread
});
If you prefer using a more Object-Oriented approach than GCD, you may also use an NSOperation (like an NSBlockOperation) and add it to the [NSOperationQueue mainQueue].
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Your code to run on the main queue/thread
}];
This does quite the same thing as dispatch_async(dispatch_get_main_queue(), …), has the advantage of being more Objective-C/POO oriented that the plain C GCD function, but has the drawback of needing to allocate memory for creating the NSOperation objects, whereas you can avoid it using plain C and GCD.
I recommend using GCD, but there are other ways, like those two which allow you to call a selector (method) on a given object from the main thread:
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait (method of NSObject so it can be called on any object)
Send - (void)performSelector:(SEL)aSelector target:(id)target argument:(id)anArgument order:(NSUInteger)order modes:(NSArray *)modes on the [NSRunLoop mainRunLoop]
But those solutions are not as flexible as the GCD or NSOperation ones, because they only let you call existing methods (so your object has to have a method that already exists and does what you want to perform), whereas GCD or -[NSOperationQueue addOperationWithBlock:] allows you to pass arbitrary code (using the block).
Swift 5+ example
DispatchQueue.main.async {
// UI code
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// UI code
}

Resources