在 C/C++ 中更改 Android 上的本机线程优先级 [英] change native thread priority on Android in c/c++

查看:22
本文介绍了在 C/C++ 中更改 Android 上的本机线程优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于线程优先级的 pthread api 非常晦涩难懂,不仅难以理解,而且在 android 上也无法使用.

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

sched.sched_priority:0 currentPolicy:0

优先级最小值/最大值:0/0

priority min/max:0/0

另外,无论我做什么,pthread_setschedparam 总是为我返回一个错误(无效参数).在我的代码中,我需要降低处理程序线程的优先级,以确保其他线程使用更多的 cpu 时间.或者,与我的进程中的其他线程相比,我可以提高我想要用作更多 CPU 的其他线程的线程优先级.

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.

我有什么办法吗?我只使用原生 C++ 代码.

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

从这篇文章看来,android 的线程是某种轻量级进程,可以修改它们的优先级setpriority 应该被使用.看起来该函数有效(getpriority before 和 after 表示优先级已被修改).但是,我在我的应用中没有看到预期的效果.

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.

推荐答案

下面是简单的答案:使用 int nice(int increment).它在 unistd.h 中声明

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

这是来自 Android 的函数代码:

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

所以,setpriority可以用来设置线程优先级.

so, setpriority can be used to set thread priority.

通过使用 nice(-10)nice(10)

这篇关于在 C/C++ 中更改 Android 上的本机线程优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆