Android中的c ++ 11多线程问题,其中某些线程未正确安排 [英] c++11 multithreading issues with Android where some threads are not scheduled properly

查看:145
本文介绍了Android中的c ++ 11多线程问题,其中某些线程未正确安排的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发基于VoIP的多线程应用程序.每个套接字都有一个c ++ 11 std::thread(包括SSL读写).数据通信的核心模块是通过JNI接口调用的C ++.

I am developing a VoIP based application which is multithreaded. For every socket there is a c++11 std::thread (including SSL read & write). The core module for data communication is in C++ which is called through JNI interface.

我的观察是,在几秒钟后初始化应用程序后,某些早先正常运行的线程无法获得运行时间.如果某个线程正在运行,那么它将持续运行3-4秒钟到30-40秒钟.

My observation is that, once initializing the application after few seconds, some threads which were running earlier normally are not getting running time. If a certain thread is running then it keeps running for a while ranging from 3-4 seconds to 30-40 seconds.

在引用更改Android上的本机线程优先级后,我还尝试将所有线程的"nice"值更改为-10,但是没有运气. 需要注意的是,完全相同的C ++代码在iOS上可以正常运行.

After referring change native thread priority on Android, I also tried changing "nice" value to -10 for all the threads, but no luck. Important to note that exactly same C++ code is working perfectly fine for iOS.

Android Native线程调度是否存在问题,或者我缺少什么?

Is there an issue with Android Native thread scheduling, or am I missing something?

推荐答案

while (...) {
 int selectResult = select( fd, ...);
 if ( selectResult > 0 ) DoSomeWork( fd );
 else nanosleep(...); /* this is the new line which solved my stalling threads */
}

我有一个类似的问题,发现对我而言,解决方案是验证那些具有永恒循环的线程(不断地执行select直到套接字上产生某些东西来生成处理程序线程),始终在以下位置调用nanosleep:在他们的循环中至少一次.

I had a similar problem, and found that for my case the solution was to verify that those threads that have an eternal loop (constantly performing select until there is something on a socket to spawn a handler thread), always call nanosleep at least once in their loop.

和您一样,我在Android上遇到了这个问题,而在iOS上没有遇到问题.

Like you, I experienced this issue on Android, and no issue on iOS.

我只能假设,Android上的JVM有时会给一个线程一个完全优先级,而该线程只是在不暂停的情况下轮询一个套接字,从而使其他有实际工作要做的线程停滞不前.但是我不知道如何验证这个假设.

I can only hypothesise that the JVM on Android sometimes would give full priority to one thread which is only polling a socket without pausing, such that other threads which had actual work to be done would stall. But I wouldn't know how to verify that hypothesis.

考虑到select已经使用了用户选择的超时,我的解决方案也很奇怪,因此我认为它无论如何都在内部休眠.显然不是在Android上.

It's also weird that my solution works, given that select already uses a user-chosen timeout, such that I would think it internally sleeps anyway. Apparently not on Android.

这篇关于Android中的c ++ 11多线程问题,其中某些线程未正确安排的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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