This question is different than what's being discussed about Main thread and UI thread in Android.
By mean of System thread - the thread which handles system UI like statusbar, notifications & other ongoing system processes, say thread which handles home-button-press, recents-menu etc...
By mean of Main thread - App's thread which handles UI (forked when process launched)
I believe it's saperate thread as busy main thread of app is not hanging your device and all other than app things work fine.
My doubt is only for the purpose:
If system can manage a separate thread for it self (to do UI work) than any process/app's-main thread; then why Apps can not have multiple threads who can handle UI (No matter how complex it's for devs!!)
Please provide references as well while pointing out answers on this.
By mean of System thread - the thread which handles system UI like statusbar, notifications & other ongoing system processes, say thread which handles home-button-press, recents-menu etc...
There may well be several threads involved in this.
I believe it's saperate thread as busy main thread of app is not hanging your device and all other than app things work fine.
More importantly, system UI is handled by separate OS processes, independent of the OS process for an app. As with most modern operating systems, in Android, a thread is owned by a process. Hence, by definition, separate processes have separate threads.
then why Apps can not have multiple threads who can handle UI (No matter how complex it's for devs!!)
That was an architectural decision, made close to 15 years ago, back when phone hardware was a lot more limited than it is today. Having a single "magic thread" is a common practice in constrained environments, as it avoids the overhead of constant checking for locks and other approaches to ensure thread-safety of data structures. While Google has done some things to try to improve on this (e.g., added a separate rendering thread), the core architectural limit remains, for backwards compatibility with older apps.
Also note that a fair amount of work is going into Jetpack Compose to try to allow for multi-threaded composables. Basically, since we now have a lot better hardware, Google is handling low-level synchronization for us in Compose, so composables can perhaps run on several threads without issue.
Related
I am a mediocore android developer for years. I like android but there's a big problem; frame drops. Even the most powerful ones can stutter so frequently while IOS devices can run at constant 60fps. I just can't understand why. I want to know it. So first thing i did was watching an I/O presentation about performance. And i didn't really understand one thing. Why can't ui and render thread run at the same time ? Yeah i know the basics like render thread can't know what to render while ui thread is doing it's thing but why can't render thread render the frame before? You can see the video here:
https://youtu.be/9HtTL_RO2wI?t=491
And here's a diagram what am i asking for:
You get the idea. I don't know about low level things about android, can anyone explain this like i'm five.
Your process' main thread is responsible for the rendering of the frames that will be presented to the user, so you should keep the code running there as fast and light as possible. If you have to do some heavy processing or access any IO (network, sdcard, etc) that may impact on the fluidity of the application since the thread may be waiting for a response.
As a good practice you should start that IO access/heavy processing on another thread to run in background and let the system decide the priority to run it, if necessary is recommended to present some feedback to the user like a ProgressBar or something to indicate that something is being processed.
Also, the Render Thread need to know what to render before it does it, so the UI Thread have to process which information the app would like to present to the user.
As #JonGoodwin points out, they both run in parallel, but usually in two cores of the same processor, as nowadays phones have at least two cores. Both threads are run in CPU, where RenderThread sends rendering commands to the GPU. Notice that this is true since API 21 (RenderThread is what enables things like ripple effect).
The problem, though, is what #LucianoFerruzzi points out: usually poor code that does too many things in the UI thread (RenderThread is not accessible, at least not with standard mechanisms).
Also, see the following episode of Android Developers Backstage: Episode 74: Graphics
I have a 2D particle system for a game engine in which I want to decouple the update loop of the particles from the main thread. I am using a thread pool implemented with boost::asio and am splitting up all the tasks into several stages and then combining the results on the main thread. This works well for me, and guarantees a limit on the total threads I have allowed for the pool (which is shared by all particle emitters which fire their own tasks independently).
I have read a lot of articles discussing std::async and std::future. This seems to be totally reasonable on windows or linux type systems where thread creation is well managed by the OS and memory is bountiful. But it seems like very little focus is spent on discussing this kind of thing in a mobile platform where thread creation may be costly. Because I am not sure how many threads might be made on these platforms it seems hard to rely on std::async in contexts where I don't know how many async calls may be in action at a given time (if each creates its own thread).
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW2
I would like to hear from an individual with multithreaded C++ mobile development experience. My question in summary is this:
If I create 20 particle effects, each with 4 concurrent async tasks, will this result in 100 threads each taking .5 mb of ram? Or does async have some magic support for being intelligent with thread creation and task sharing?
Alternatively will async bog down the main thread (if not being explicit with the thread creation rule) effectively lagging my gameplay for relatively low-priority particle effects?
If so, what context is async actually useful in on mobile as it seems thread creation is something you'd like to be a little more explicit about on these devices.
I have reposted my question from Android Enthusiasts here, as this is more of a programming question, and it was recommended.
Anyway. Here it is:
I am making an app, that changes the build.prop of key values for a ROM. However, Android often gives me an ANR warning, as I am doing all the work on the UI thread. On the Android documentation, it tells me that I should use worker threads, and not do any work in the UI thread. But, I am building this system app to go with a ROM for a single core device.
Why would I want to use worker threads, as isn't this less efficient? As, Android has to halt the UI thread, load the worker thread, and when the UI is used again, halt the worker thread and load the UI thread again. Isn't this less efficient?
So, Should I use worker threads (Which slows the UI thread down anyway) or just do all of my work on the UI thread *Even if the application UI is really slow)?
If your users were robots, your logic would make perfect sense. No context switching equals (very slightly) less overall computation time. You could benchmark it and see how much exactly.
However, in the present (and near future) your users will most likely be humans and with that you need to start thinking of psychology: A moving progress bar or responsiveness in general will give your users the impression that the the task is actually taking a shorter time than without any sort of feedback. The subjective speed is much higher with feedback.
There exist numerous papers on the subject of subjective speed, the first one I could find on the web has a nice comparison of progress bars in a video (basically, some bars seem to go faster than others, thus reducing the subjective overall wait time).
Use worker threads.
As you've said, doing everything on the UI thread locks your UI until the operation is completed. This means you can't update progress, can't handle input events (such as the user pressing a cancel button), etc.
Your concern about the speed of context switching is misplaced - this happens all the time anyway, as core system processes and other apps run in the background. Some quick Googling shows that context switching a thread within the same process is typically faster than a process-level context switch anyway. There is slightly more overhead introduced by creating the threads and then the subsequent context switches, but it's likely to be minute - especially if you only have the 1 thread doing the work. For the reasons I've listed above alone (UI updates and the ability to accept user input), take the few-millisecond overall performance hit.
I recently had problem getting my physics to stop racing ahead of my rendering (they were on the same thread), After a few months, I resolved the problem in about 20 minutes by creating a new thread and putting by physics into that.
I find that having them completely separate from each other gives me far greater control and now my sprites are moving consistently across all screens at all frame rates.
My question is, is it 'better' to put logic and rendering in the same thread or separate threads? The latter seems better to me but does it cause any problems? (does if affect battery life for example?)
Thank you
Yeah it is definitely better to use multiple threads, especially if the calculation is non-trivial, in which case you could experience the dreaded "Activity Not Responding" dialog.
Something that I would definitely look into would be AsyncTasks http://developer.android.com/reference/android/os/AsyncTask.html . Essentially, you would perform all of your physics calculation in the doInBackground method(which is running in a background thread) and then periodically call publishProgress from within that(which will execute the 'onProgressUpdate' callback where you will do all of your rendering on the UI thread).
Actually using different threads for performing logic and rendering UI is really and always appreciated.and it correct also.
But to handle/manage the multiple thread is the harder responsibility for a programmer.
And as the threads also increase the battery consumption, so we should always use thread very carefully.
So the final outcome is use threads but carefully. because thread are useful is used optimally but dangerous is not used carefully.
You said...
"I'm using surfaceView which as I understand it, uses a separate thread for rendering (separate from the UI thread) - so I have 3 threads"
It sounds like you're assuming that by extending SurfaceView, you're automatically provided with another underlying thread for the Surface which is separate from the UI thread. I believe that this is NOT the case.
From the Android developer reference for SurfaceView: "One of the purposes of this class is to provide a surface in which a secondary thread can render into the screen."
The key word being can. You still have to spawn the separate thread yourself, the SurfaceView just makes it easier to draw to a canvas in a separate thread.
If you take LunarLander as an example, it has just two threads: the UI thread, and a manually-spawned 'LunarThread' in which the physics are updated and the canvas (via SurfaceHolder.lockCanvas()) is drawn to, as fast as possible, independent of the UI thread.
Just wondering if threading with one processor improves things for me.
I am building an application that performs data intensive calculations (fft on pcm data) while a UI is running and needs to run smoothly.
I have been looking at AsyncTask but was thinking:
If I have a single core processor (600 MHz ARM 11 processor) running on my Optimus One, will threading make a difference? I thought for threads to run independantly you would need multiple processors? Or have I gone wrong somewhere?
In order to guarantee responsiveness, it is imperative to leave the main or UI thread to do the UI things. This excludes intensive drawing or 3d rendering in games. When you start to do computationally intensive things in your main thread, the user will see lag. A classic example:
on a button click, sleep(1000). Compare this with, on a button click, start an AsyncTask that sleeps(1000).
An asynctask (and other threading) allows the app to process the calculations and UI interactions "simulataneously".
As far as how concurrency works, context switching is the name of the game (as Dan posts).
Multithreading on a single core cpu will not increase your performance. In fact, the overhead associated with the context switching will actually decrease your performance. HOWEVER, who cares how fast your app is working, when the user gets frustrated with the UI and just closes the app?
Asynctask is the way to go, for sure.
Take a look at the Dev Guide article Designing for Responsiveness.
Android uses the Linux kernel and other specialized software to create the Android Operating System. It uses several processes and each process has at least one thread. Multi-threading on a single (and mutiple) processor hardware platform is accomplished by context switching. This gives the illusion of running more than one thread per processor at a time.