IOS - Threads are stopped during web service call - ios

I am running an application with multiple threads. My application has set of queue objects(simply array).The input for the thread will be from this queue. Each thread will get a queue object as an input. And I am creating and starting this thread in simple manner as below.
threadOne = [[NSThread alloc] initWithTarget:self
selector:#selector(initThread:)
object:nil];
[threadOne main];
Likewise I am starting multiple available threads for every objects.
When I run my application in debug mode during my webservice call, My current running thread doesn't wait for response (approximately my webservice call will take 2-3 seconds to generate response). Here my queue process gets stopped due to web service call.
Below is the code for reference.
dispatch_sync(dispatch_get_main_queue(), ^{
[service genID:self action:#selector(genHandler:) username: username password:password ];
});
I want to run multiple threads in parallel, in my application. Is there any solution to accomplish the above.

You probably have a deadlock because you are calling
dispatch_sync(dispatch_get_main_queue()
from main thread. You can find an excellent explanation in this answer.
As a side note, I would recommend using NSOperationQueue or Grand Central Dispatch, because Apple does not recommend using NSThread objects directly:
In the past, introducing concurrency to an application required the creation of one or more additional threads. Unfortunately, writing threaded code is challenging. Threads are a low-level tool that must be managed manually. Given that the optimal number of threads for an application can change dynamically based on the current system load and the underlying hardware, implementing a correct threading solution becomes extremely difficult, if not impossible to achieve. In addition, the synchronization mechanisms typically used with threads add complexity and risk to software designs without any guarantees of improved performance.
Both OS X and iOS adopt a more asynchronous approach to the execution of concurrent tasks than is traditionally found in thread-based systems and applications. Rather than creating threads directly, applications need only define specific tasks and then let the system perform them. By letting the system manage the threads, applications gain a level of scalability not possible with raw threads. Application developers also gain a simpler and more efficient programming model.

Related

Swift, number of threads in app

I am making an app for website. I use JSON to get data. I want to load all posts in threads (1 post - 1 thread). How many threads I can make? Should I control the number of threads?
With Cocoa you usually don't work with Threads directly. Grand Central Dispatch (GCD) is an API that handles this for your. You just have to partition your task into small managable chunks, dispatch them onto a background queue and the rest is handled for you. You don't need to worry about creating threads, how many are currently running etc. When you dispatch enough work on one (or possibly more) queues, the CPU is going to run at maximum load.
You can also use NSOperationQueue, which has the ability to throttle the execution to some extend or cancel currently running tasks (not possible with GCD).
Unless you are doing anything unusual there is no need to use NSThread directly. Use GCD when you just need to perform a simple small task asynchronously. Use NSOperationQueue when you need more control, like cancelling submitted tasks or setting priorities. It's API is also a bit higher level and in Objective-C. GCD is a C level API, so for example it can't catch ObjC-Exceptions. NSOperationQueue uses GCD internally, so both should work equally well.

What is the difference between 'thread' and 'queue' in iOS development? [duplicate]

This question already has answers here:
Use of the terms "queues", "multicore", and "threads" in Grand Central Dispatch
(3 answers)
Closed 8 years ago.
I am new to iOS development. Now I am quite confused about the two concepts: "thread" and "queue". All I know is that they both are about multithread programming. Can anyone interpret those two concepts and the difference between them for me?
Thanks in advance!
How NSOperationQueue and NSThread Works:
NSThread:
iOS developers have to write code for the work/process he want to perform along with for the creation and management of the threads themselves.
iOS developers have to be careful about a plan of action for using threads.
iOS developer have to manage posiable problems like reuseability of thread, lockings etc. by them self.
Thread will consume more memory too.
NSOperationQueue:
The NSOperation class is an abstract class which encapsulates the code and data associated with a single task.
Developer needs to use subclass or one of the system-defined subclasses of NSOperation to perform the task.
Add operations into NSOperationQueue to execute them.
The NSOperationQueue creates a new thread for each operation and runs them in the order they are added.
Operation queues handle all of the thread management, ensuring that operations are executed as quickly and efficiently as possible.
An operation queue executes operations either directly by running them on secondary threads or indirectly using GCD (Grand Central Dispatch).
It takes care of all of the memory management and greatly simplifies the process.
If you don’t want to use an operation queue, you can also execute an operation by calling its start method. It may make your code too complex.
How To Use NSThread And NSOperationQueue:
NSThread:
Though Operation queues is the preferred way to perform tasks concurrently, depending on application there may still be times when you need to create custom threads.
Threads are still a good way to implement code that must run in real time.
Use threads for specific tasks that cannot be implemented in any other way.
If you need more predictable behavior from code running in the background, threads may still offer a better alternative.
NSOperationQueue:
Use NSOperationQueue when you have more complex operations you want to run concurrently.
NSOperation allows for subclassing, dependencies, priorities, cancellation and a supports a number of other higher-level features.
NSOperation actually uses GCD under the hood so it is as multi-core, multi-thread capable as GCD.
Now you should aware about advantages and disadvantages of NSTread and NSOperation. You can use either of them as per needs of your application.
Before you read my answer you might want to consider reading this - Migrating away from Threads
I am keeping the discussion theoretical as your question does not have any code samples. Both these constructs are required for increasing app responsiveness & usability.
A message queue is a data structure for holding messages from the time they're sent until the time the receiver retrieves and acts on them. Generally queues are used as a way to 'connect' producers (of data) & consumers (of data).
A thread pool is a pool of threads that do some sort of processing. A thread pool will normally have some sort of thread-safe queue (refer message queue) attached to allow you to queue up jobs to be done. Here the queue would usually be termed 'task-queue'.
So in a way thread pool could exist at your producer end (generating data) or consumer end (processing the data). And the way to 'pass' that data would be through queues. Why the need for this "middleman" -
It decouples the systems. Producers do not know about consumers & vice versa.
The Consumers are not bombarded with data if there is a spike in Producer data. The queue length would increase but the consumers are safe.
Example:
In iOS the main thread, also called the UI thread, is very important because it is in charge of dispatching the events to the appropriate widget and this includes the drawing events, basically the UI that the user sees & interacts.
If you touch a button on screen, the UI thread dispatches the touch event to the app, which in turn sets its pressed state and posts an request to the event queue. The UI thread dequeues the request and notifies the widget to redraw itself.

What I should use for parallelisation of frequent HTTP requests to the REST server in iOS application: GCD or NSThread?

I'm developing an application which must extract new messages for user from the server. I have implemented this as a timer which fires every 2 seconds and call a selector which is a method that implement HTTP request and server respond processing. So I think it is quite a bad idea to do this in a main thread.I have no experience with multithreading in iOS. So I want to know what fits well for parallelizing of this task: GCD or NSThread?
You should work as far up the API stack as possible. That way you can concentrate on programming functionality and not managing threads. GCD uses threads that the system has gotten going anyway and its much more efficient than managing your own code. Its even better to aim to encapsulate your networking into NSOperations that can then be put on an NSOperationQueue and these will be executed on one or more background threads, whatever the system deems is a good number for the current power status and other things like that.
The benefit of NSOperation over a pure GCD approach is that operations can be cancelled. Once a block is committed to GCD it has to run no matter what.
If you want to encapsulate your HTTP requests in NSOperations you might be interested to know that someone has already done this for you. AFNetworking is one of the most widely regarded iOS networking stacks and uses NSOperations as its base to build on and as such is very easily multi threaded.
A good idea would be to try and encapsulate your parsing code into an NSOperation and then as your network request operations return you can create parsing operation instances and put them on another queue for processing in the background.

What is good practice for using NSOperation and NSOperationQueue?

I just start using NSOperation and NSOperationQueue. I really want to know what should be better practice for using them.
Should I create a only one queue for whole app, or should I create one queue for each specific type of task? What is the effect if I create so many queues?
It depends on what you're using them for. If you're using them for performance, maxing out the CPU, then there is little point going much beyond how many cores you expect to have.
If you're offloading processing just to keep the UI responsive, but you're not particularily concerned about maxing out performance, I'd just use the default background queue for simplicity.
If you're using sequential background queues to trigger actions on external events ( network request completion, for example), then it doesn't do any harm to use a bunch, as they won't lead to a lot of threads trying to run concurrently.
There are many instances where you can simplify the design using an operation queue.
NSOperationQueues are built on top of GCD, and AFAIK, there is no performance impact of having loads of queues, as long as they're not trying to execute concurrently.
Read up on the Executing Operations section of the Apple Concurrency Guide. It depends of course on your implementation and application but in summary ther can only be a certain amount of NSOperations running concurrently and increasing the number of NSOperationQueues won't serve any benefit to you. So my recommendation would be to opt for 1 or fewer queues if your design can allow it.

when to use multithreading in iOS development?

beside heavy processing, should multithreading mainly be used when you have a not quite responsive UI? or does it have other considerations?
How can I know if my application should have multithreading or not?
One of the Important Application of thread in ios is during network communication.Whole your app is communication with server and if you want to show busy view on UR UI you need to create thread in such scenario to perform network communication in background thread.
In IOS 5,You can opt for GCD(Grand Central Dispatch)Instead of thread to perform same functionality..
Basically in iOS development Threads are used when you don't want to affect you UI by a process which will take long time to complete. for example when you make a connection to parse xml,json,image data etc then you don't want to stop user interaction at that time you can use threads.
you can start a thread by using NSThread.
Things to have in mind before using threads -
You should never do a graphical change in a thread. If you need to
that in a thread then you can do only on main thread.
Never use a NSTimer in a secondary thread, because your thread may
complete before timer execution so timer may not run.
whenever you want to perform a long process then you can use thread.
The use of threading in ios is to ensure hussle-free and seamless experience by the end-users.
You can implement thread whenever you want to extract some resource over the network such as parsing or data retrieval and you don't want the ui to be affected as application would run on main thread and the web-operation on your custom thread.
You may want to use the thread when you need to have concurrent operations or simultaneous such as in game when you hae to have multiple animations on same object at same time.There can be quite a large number of scenarios which may need threading.
You may read Concurrency Programming Guide By Apple
and Thread Management
but threads may be an overhead in the application as it needs memory allocation and large operations on thread may affect the performance so use it when it can't be avoided.
You can use NSThread,NSOperations to create threads .GCD is deprecated now.

Resources