Why are native threads different when the application is in the background?

In my application, I use my own streams to process audio data. The code looks something like this:

std::thread([this] () { while (enabled) { if (condition()) { process(); } usleep(100); } }); 

This works great when the application is in the foreground. In the background, the processing is not fast enough, and I get buffering. It only works with usleep in the background. The value I pass to usleep doesn't matter. It also does not work with lower values. I also tried std::this_thread::sleep_for(std::chrono::microseconds(100)) , but that doesn't matter.

I need to use usleep or something similar to avoid using a large number of processors and thereby reduce battery life.

What can I do to make native threads behave the same when the application is in the background?

+5
source share
2 answers

Android seems to set the thread priority for background apps lower, unless explicitly stated otherwise. This documentation mentions

Typically, threads in the foreground group receive about 95% of the total execution time from the device, while the background group receives about 5%.

Which would explain your underutilization. You should try to increase the priority as described here. Sounds like a related video .

+4
source

Maybe I'm wrong, but it looks like you should prioritize your thread in the CPU. When the application is in the background (or destroyed, but with live threads), the threads are prioritized by the OS and their activity decreases most of the time, especially if they were initialized with the default priority - BACKGROUND (which is low).

Try working with HandlerThread (android.os). That way you can determine your priority, and in your case I can try THREAD_PRIORITY_AUDIO

Java: (sorry for the lack of C ++)

 HandlerThread thread = new HandlerThread("MyThread", Process.THREAD_PRIORITY_AUDIO) 
0
source

Source: https://habr.com/ru/post/1263392/


All Articles