What is a main and background threads in iOS? - swift

can you guys explain what a background and main threads are?
I'm a junior iOS Developer(swift) and I've been programming for 6 month and never heard of this before.
Thanks in advance.

Threads allow you to execute multiple code paths concurrently inside a single application.
iOS apps have a main thread which processes all the UI logic and base of your app. Sometimes you need to push your heavy code (such as a network call) to a different (background) thread so it doesn't clog up the main thread and block your UI from changing for example. It also allows you to do multiple things at one, or run multiple network calls.
This article explains in more detail:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html#//apple_ref/doc/uid/10000057i-CH1-SW1

Related

Multithreading in ios

Need your help.
In my application, i want to implement a background process which keeps running continuously and downloads the updated data and stores it in document folder.
And my main thread should keep checking the document folder and display the updated data in view control.
The child thread should end once the view disappears. and start again once the view appears.
What is the best way to do it? NSThread or NSOperationQueue? What precautions are required?
I also have to access few variables of the class. So is should be thread safe.
Thanks in advance.
Regards
If you do not need to update a progress bar or something in iOS5 there is one great API method + sendAsynchronousRequest:queue:completionHandler: that allows you to run async download as a block inside NSOperationQueue. If not you should look into third party libs such as ASIHTTP request or https://github.com/AFNetworking/AFNetworking(probably better the last one) or you need to build you own download manager, not a simple task
there are two ways to do it..
First: You use NSOperationQueue which is a bit bulkier as it is build on GCD but does have some extra features.
Second: You use GCD (grand central dispatch) looking at requirements I would say GCD seems fine as you can easily access any thread(main or background) this would be slightly quicker.
You can have a look at - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg This method creates a new thread in your application, putting your application into multithreaded mode if it was not already. In your viewDidDisappear, you can stop the task when your view disappears
From Apple Docs. Apple encourages to investigate the alternative Mac OS X technologies for implementing concurrency. This is especially true if you are not already familiar with the design techniques needed to implement a threaded application. These alternative technologies simplify the amount of work you have to do to implement concurrent paths of execution and offer much better performance than traditional threads.
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/AboutThreads/AboutThreads.html#//apple_ref/doc/uid/10000057i-CH6-SW2

NSOperationQueue many threads

In our iPhone application we have several tabs and selecting each tab triggers network connection. In the past we were just detaching new thread for each connection. And after several very quick tab switches application was becoming unresponsive.
Now we decided to use operation queue which supposed should control number of threads and should not allow the application to become unresponsive. But now the app becomes unresponsive even with fewer quick switches (although now it recovers from unresponsiveness quicker).
I ran the app on device from xcode and paused it after several quick switches to see the number of threads. And what I have found is that there are several threads with the following stack:
0 __workq_kernreturn
2 _init_cpu_capabilities
Any idea what are these threads and how to get rid of them?
One of the big benefits of using NSOperationQueue is that you can forget about threads and let the system worry about that for you. It sounds like the root of your problem is that you've got several operations running simultaneously that are no longer needed. Rather than worrying about the specific threads, consider getting those operations to terminate so that they're no longer using up computing resources.
For what it's worth, my guess is that those threads are being managed by Grand Central Dispatch. GCD will create worker threads to process blocks (and operations), and it'll be as efficient as it can about that.
the important part of your problem does not likely lie in the internal/private implementation of worker threads. a good implementation will likely employ a thread pool because creating one thread per operation would cost a lot. operations can reuse and hold on to idle threads.
the important part (likely) lies in your use of the public apis of the implementation you have chosen.
one obvious implementation to support in this case is operation cancellation: -[NSOperation cancel]. when somebody navigates away from a view which has a pending/unfinished request, simply cancel it (unless you'll need the data for caching).
many implementations may also benefit by making requests less often. for example: if your server results only update about once per hour, then it doesn't make sense to request it 'about every minute'.
last point: a connection can use a worker thread itself - check the apis you are using to reduce this if it's a problem.

OK to launch background threads from other background threads? (NSObj)

This question is for those of you who, unlike myself, truely understand multi-threading in cocoa apps. Here, briefly, is the situation:
Situation:
My app achieves concurrency by using the methods provided in NSObject. Please tell me if it is OKAY to do the following:
1) My main view controller launches some work in the background to free up the UI:
[self performSelectorInBackground:#selector(loadImages:) withObject:nil];
2) The background work divides its task into several smaller tasks on more background threads so that each task is updated as it finishes (as opposed to when all tasks finish):
[self performSelectorInBackground:#selector(loadOneImage:) withObject:nil];
Rationale:
This was the only way I could invent to get individual tasks (loading/drawing of custom UIViews) in a set to update in UI AS each is completed. Otherwise, all tasks only get updated when the last task in the group has completed...
yes, you may use performSelectorInBackground:... calls to spawn secondary threads from secondary threads.
if you have a lot threads to spawn (in this manner), consider an NSOperationQueue. Otherwise, you may end up with a ton of background threads. 100 threads (for example), each loading one image in a mobile device is not a good use of resources - nor will it be responsive. NSOperationQueue allows you to cap the max number of threads/workers, and reuses worker threads.
note: '100 threads' was used because the number is far beyond logical for the hardware (the question is tagged iPhone). if your image loading is all in memory, just use a serial (1 worker at a time) NSOperationQueue - NSOperations may specify priority. if images are being downloaded, then you may want to stick to 4 or less.
things are different on OS X, where there are more cores and resources available, so these numbers will change as the hardware platform change. on OS X, you can successfully use 100 threads in one app, although it is unusual to need anything near that many threads for most apps.
There's nothing wrong with this approach as far as I can see. According to the doc, performSelectorInBackground:withObject: just spawns another thread and executes your selector there. It doesn't list any limitations. Just don't forget to set up autorelease pools in each method that you call via performSelectorInBackground:withObject: to not leak any memory.
One critical condition you should make sure. Both threads which are running in background should not have any dependency. If they have, then you may end up in inconsistency.
So beter if you go for operation queues rather than spawning thread from another background thread.

Should I use Threads to accelerate the application

I've got an game app displaying a lot of images that need to be processed before being displayed. The set of images need to be refreshed with new ones every 2 seconds.
to speed up the display : While the first set of images is displayed, I'd like to prepare in background the next set.
I've got a specific class "board" that I could call in background to generate the "nextSet" while "currentSet" is being used by the player.
What is the best way to do it ?
Threads seems to be the thing to do ... is yes, do where may I find some examples of code triggering that generation in background ?
cheeerio,
Tibi.
Sounds like a producer/consumer situation. I suggest you look at queues to solve this. You would have one thread processing images in the background (producer) and placing then in the queue. Then you have your UI that consumes them when they are ready by showing them to the user. In iOS4 there is enhanced support for concurrency related tasks and Apple have some excellent guides on the topic.
Concurrency Programming Guide
Grand Central Dispatch
Good luck
This Threading Cocoa tutorial is good enough to start. They also have sample code
For the question: should you use NSThread.
Technically, yes, you should. For heavy IO like this, perform on the background will not freze your UI and it will improve your User Experience as well. But, be careful when using thread, it has its difficulty like data sharing, deadlock...

iphone app photo upload to server from app threads

I have an app that needs to upload a least 5 photos to a server using API call available with the server. For that I am planning to use threads which will take care of photo upload and the main process can go on with the navigation of views etc. What I cant decide is whether it is OK to spawn five separate threads in iphone or use a single thread that will do the upload. In the later cases obviously it will become quite slow.
Basically an HTTP POST request will be made to the server with the NSMutableURLRequest object using NSCOnnection.
More threads mean more complexity and sync issues, but I can try to write code as neat as possible if it means better performance than a single thread which is simple but is a real stopper if performance is considered.
Anybody with any experience in this kinda app. ??
I would suggest using one extra thread and queuing the uploads, one after the other. You'll end up clogging the network interfaces if you try 5 uploads concurrently. Remember that the iPhone will often be on a 3G or even EDGE connection, not always WiFi, so photo uploads can be really slow, and even slower if there are 5 at once.
You could probably benefit from using NSOperation and NSOperationQueue to nicely handle the ugly threading for you. Wrap up an upload process into an NSOperation, and then queue 5 of them for each image. Should work quite nicely.
Jasarien thanks for the bit on NSOperation and NSOperationQueue. It did simplyify in great measure. But right now I hve run into a major issue.
I spawn an extra thread from the main thread. This thread queues up each of the picture upload operation. So this thread queues up 5 picture opload operations in a queue. This is absolutely fine when working with Mac PC. Now when I push the app to the device, only one pic upload is successful and the rest fails. Most of the cases of failure are due to server time out error. So basically I am wondering, whether NSOperationQueue ensure only one operation at a time or not ? I mean if the first pic upload is in progress and say the next operation is already added in the queue. Would it create an extra thread for the second operation too while the first one is running ? I think as the name suggests, it must wait in the queue until the previous one is done. Not sure how to go abt doing it. I am uploading pic which are taken with iphone camera.