Jan Deinhard
Jan Deinhard

Reputation: 20195

Why do native threads behave different when app is in background?

In my app I use native threads to process audio data. The code looks very much like this:

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

This works fine when the app is in foreground. In background the processing is not fast enough anymore an I get buffer-underruns. It only works without usleep in background. The value I pass to usleep does not make a difference. It does not work with smaller values as well. I also tried std::this_thread::sleep_for(std::chrono::microseconds(100)) but it does not make a difference.

I have to use usleep or something similar to avoid high CPU usage and thereby to save battery lifetime.

What can I do to make natives threads behave the same when the app is in background?

Upvotes: 5

Views: 511

Answers (2)

Barak
Barak

Reputation: 1429

I might be wrong but it sounds like you should prioritize your thread in the CPU. When the app is in background (or destroyed but with live threads), threads are being prioritized by the OS and their activity is lowered 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 define its priority, and in your case i might try THREAD_PRIORITY_AUDIO

Java: (sorry for no c++)

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

Upvotes: 1

Matthias247
Matthias247

Reputation: 10406

It seems like Android sets the Thread priority for background apps lower if not explicitly specified otherwise. This documentation mentions

Generally, threads in the foreground group get about 95% of the total execution time from the device, while the background group gets roughly 5%.

Which would explain your underruns. You should try to increase the priority like it's described there. The linked video also seems helpful.

Upvotes: 5

Related Questions