Pavel Pavel - 5 months ago 46
Android Question

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));


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.

Answer Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download