Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can we create multiple main thread in single application?
Why all UI changes made in main thread?
I have faced these question in interviews. I am unable to find any solution. Can any one help me to find the answers of this question? That will help me in future interviews and implementations in iOS app.
Thanks in advance!
There is only ever one main thread in your application, however tasks from multiple dispatch queues may execute on this thread. Tasks that are dispatched on the main queue are guaranteed to run on the main thread.
Generally with GCD you do not think about threads, but rather queues which are abstracted from the underlying threads. They provide a level of abstraction that makes it easier to manage tasks without being concerned about the number or state of the threads that are being used.
THe autolayout engine performs a number of calculations and applies rules in order to arrive at a layout solution. If the properties of a UI element change then the autolayout solution is invalidated and needs to be recalculated.
As the main queue is a serial dispatch queue, dispatching UI updates onto the main queue ensures that either the autolayout calculations are being performed or a UI property is being updated but not both at the same time (of course there are more than just these two activities happening on the main queue, but we are just addressing autolayout here)
No, there is only one main thread for the application that is created by system for application. Main thread is the thread that directly gives changes to user. Thread which is directly connect with user you can said.
Check the Apple Documentation, It states,
The main queue is automatically created by the system and associated with your application’s main thread. Your application uses one (and only one) of the following three approaches to invoke blocks submitted to the main queue:
Calling dispatch_main
Calling UIApplicationMain (iOS) or NSApplicationMain (OS X)
Using a CFRunLoopRef on the main thread
As with the global concurrent queues, calls to dispatch_suspend,
dispatch_resume, dispatch_set_context, and the like have no effect
when used with queues returned by this function.
Now, let's take an example, If you are downloading an image and want to display it to user. Now if you will download it on main thread then it will block other UI till it completed download. So, you should not download it on main thread or synchronously . you should download it asynchronously and when download is completed, you should display it to user on main thread, so it will quick displayed to user after download is completed.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to have some clarify about it.
I know that I need to update UI in main thread. Are there anything else?
What I need to do in main thread and what in background threads?
In addition to UI updates, as a broader thread-safety strategy, people will often dispatch their model updates to the main thread as a simple synchronization technique, too.
Synchronization is ultimately the process of assuring that an object is in a logically consistent state, i.e. that while an object is being used on one thread, that it isn't simultaneously being mutated by some other thread. Traditionally, one might accomplish this by employing locks (e.g. NSLock, #synchronized, etc.) but you can also achieve this by dispatching all interaction with a particular object to a serial queue. While you can replace locks with a dedicated serial queue, in many cases it's just as easy to dispatch all updates to the object in the main queue. It turns out to be a convenient way to synchronize your model objects that might otherwise would have been used/mutated by separate threads.
For more information, see the Eliminating Lock-Based Code section in the Migrating Away from Threads chapter of the Concurrency Programming Guide.
It all depends.
Modern OS take advantage of the multiple cores or virtual CPUs, so when you run your app, the OS defines what to run where, and usually your program runs in multiple threads.
If there are data dependencies, then you should run things in specific threads, unless you run stuff in background or different threads, then you can implement notifications to ensure that the data you need is ready when you need it. You should also take into account the thread safe nature of the the different ways to define properties. So... other than the UI stuff in main, you can run anything pretty much wherever you want.
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.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Tell me if this make sense. This is an iOS question.
I'm seeing code where it is already in the main thread, but the code would dispatch_async all sorts of UI code to the main thread's queue. Layouts, animations etc etc.
I was told this some how speeds up responsiveness (example, when pushing a view controller, you would dispatch other UI ops there so it won't block the push transition.
This doesn't make sense because first it is dangerous, second, it doesn't guarantee when the UI code gets run(even though it will probably run with milliseconds). The only good reason I can see is for it to guarantee that the UI code is not accidentally run in a different thread.
What do you guys think?
There are definitely times you employ this pattern of dispatching back to the main queue, so I might not be too quick to dismiss it or label it as "dangerous" (though the way you characterize it, it does sound suspicious). You should share some code samples of how you're seeing this pattern being used, and we can comment further.
When would you dispatch to the main queue? The prototypical example is when you're doing something on a background queue, but then want to dispatch the UI updates back to the main queue, e.g.:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// do something time consuming here, like network request or the like
// when done, update the UI on the main queue:
dispatch_async(dispatch_get_main_queue(), ^{
// update the UI here
});
});
But I'm assuming this is not the sort of dispatch to the main queue you're talking about. I'm assuming from your comment where you have something on the main queue dispatching asynchronously right back to the main queue itself.
The reason you would do that is if you don't want the dispatched code to run immediately, but rather to be queued for the next iteration of the run loop. This lets the autorelease pool drain, lets the current method complete (and release any resources it might have been using), lets other dispatched tasks run first, gives the UI a chance to reflect any changes you may have initiated, etc.
A few examples of when some developers might do this include:
You might use this pattern if you want a method call itself recursively, but you want to yield back to the run loop, to let resources be freed, let the UI reflect any changes, etc. You're basically saying "ok, let this method finish, but in the next run loop, run this method again."
A little more suspect, I've seen this pattern in viewDidLoad where you want to give auto layout a chance to "catch up" and update the frames. E.g. there is a common third-party progress indicator that won't work if you just invoke it from viewDidLoad, but it works if you dispatch that update back to the main queue.
Having articulated reasons why I've seen developers dispatch back to the main queue from the main queue, itself, I must confess that many of these patterns suffer from code smell and are often better accomplished via different patterns. But these are a few examples that I've seen.
But, again, if you want assistance on your particular code sample, you have to share it with us. We can't tell what the developer intended without seeing the code sample.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
is it possible to call an action that contain heavy operations several times? like save button (I save the first object) and want to add others, but the app becomes so slow and I can't navigate to other views
You can always play around with heavy data saving related tasks in the background. You can distribute the content related stuff to various threads (queues), you need to separate the stuff which you are saving and if it is blocking your UI and making your app slow then you need to perform these heavy operations in the background.
Make sure, you do NOT perform any UI updation operation in the background. Try reading about GCD (how it works), how you can create a background Queue etc and how you can play around with it. I assume you might be using core data in order to save the contents on save button. Try reading about the Parent/Child Manage Context Objects. Play around with it a bit and move your heavy task to background, updation of UI will always be on Main or UI thread (which you can always do it by calling get_main_queue() if you are working with dispatch queues). Happy Coding. If you have specific code, which is doing this, then let us know. We will be glad to help. :)
You need to make sure that you aren't tying up the main UI thread of your application. A potential easy fix is to do your save operation on a different thread. Here is an example of how to do just that using Grand Central Dispatch: iPhone - Grand Central Dispatch main thread
Example:
//notice this saveQueue is a new dispatch queue that's been created.
dispatch_queue_t saveQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(saveQueue, ^{
//this command represents your long running operation
doSaveOperation();
dispatch_async(dispatch_get_main_queue(), ^{
//always update your UI on the main thread!
[self showCompleteMessage];
});
});
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.