Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change native thread priority on Android in c/c++

Insanely obscure pthread api for thread priority not only outlandishly incomprehensible, but also it just doesn't work on android.

So, is there a way for me to reduce or increase a thread's priority?

int currentPolicy;
struct sched_param sched;
status = pthread_getschedparam(pthread_self(), &currentPolicy, &sched);
printf("sched.sched_priority:%d currentPolicy:%d", sched.sched_priority, currentPolicy);
printf("priority min/max:%d/%d", sched_get_priority_min(currentPolicy), sched_get_priority_max(currentPolicy));

outputs:

sched.sched_priority:0 currentPolicy:0

priority min/max:0/0

Also, no matter what I do, pthread_setschedparam always return an error for me (Invalid argument). In my code, I need to reduce priority of my handler thread to make sure that the other thread uses more cpu time. Or, alternatively, I could boost thread priority of my other thread that I want to use as more cpu compared to other threads in my process.

Is there any way for me to do that? I use native c++ code only.

Edit: From this post looks like android's threads are some kind of light weight processes and to modify priorities for them setpriority should be used. It looks that the function works (getpriority before and after indicates that priority was modified). However, I don't see expected effect in my app.

like image 761
Pavel P Avatar asked Jul 01 '13 05:07

Pavel P


2 Answers

Android threads are Linux threads. Nothing special about them.

setpriority() alters the thread's "nice" value, which affects the priority at which the thread is scheduled.

pthread_setschedparam() can be used to change the policy as well.

Generally speaking, you can't raise the priority or change its policy without elevated privileges (CAP_SYS_NICE). You can lower it, or raise it back to "normal" priority.

If you use adb shell ps -t -p you can see the priorities assigned to every thread. This information is also included in Dalvik stack dumps.

Dalvik uses setpriority() to temporarily raise the GC thread's priority if necessary (to avoid priority inversion). If you look at this bit of code around line 625 you can see it. You can also see the call to set_sched_policy(), an Android library function that changes which cgroup the thread is in.

like image 180
fadden Avatar answered Sep 20 '22 13:09

fadden


Here's simple answer: use int nice(int increment). It's declared in unistd.h

here's the code of the function from Android:

int nice(int increment)
{
    int  priority = getpriority(PRIO_PROCESS, 0);
    return setpriority( PRIO_PROCESS, 0, priority+increment);
}

so, setpriority can be used to set thread priority.

I actually got difference as expected in my code by using nice(-10) or nice(10)

like image 38
Pavel P Avatar answered Sep 19 '22 13:09

Pavel P