在Android上,我们拥有C ++本机应用程序,该应用程序使用POSIX pthread库创建新线程。我们正在使用pthread_attr_setstacksize
将堆栈大小设置为512K(在创建新线程之前),但是堆栈大小始终默认为1M。
以下是示例代码,
1 #include <iostream>
2 #include <pthread.h>
3 #include <sys/time.h>
4 #include <sys/resource.h>
5
6 void* Function(void *ptr)
7 {
8 pthread_attr_t attr;
9 pthread_attr_init(&attr);
10 size_t get_default_size;
11 pthread_attr_getstacksize(&attr, &get_default_size);
12 std::cout<<pthread_self()<<" Stack size = "<<get_default_size<<std::endl;
13 return NULL;
14 }
15
16 int main ( int argc, char *argv[] )
17 {
18 pthread_attr_t attr;
19 pthread_attr_init(&attr);
20 if ( pthread_attr_setstacksize(&attr, 1024 * 512) == 0)
21 std::cout<<"Setting stack size successful"<<std::endl;
22
23 pthread_t thread_id;
24 /* creating a new thread with thread stack size set */
25 pthread_create(&thread_id, &attr, &Function, NULL);
26 pthread_join(thread_id,0);
27 }
所以,当我运行上面的代码时,我总是得到以下输出,
CT60-L1-C:/data/data/files $ ulimit -s
8192
CT60-L1-C:/data/data/com.foghorn.edge/files $ ./nativeThread
Setting stack size successful
520515536112 Stack size = 1032192
CT60-L1-C:/data/data/files $
但是,ulimit -s
的堆栈大小为8192K,我在源代码中显式将堆栈大小设置为512K(第20行),pthread_attr_getstacksize
的输出(第6行)。 11)从线程始终为1M。
所以我有两个问题:
pthread_attr_setstacksize
正确的方法来设置堆栈大小吗?ulimit -s
对创建的新线程的堆栈大小没有影响?感谢您的帮助
我尝试将ulimit -s
更改为其他大小,但我始终始终将线程的堆栈大小设为1M。感觉我们无法更改Android上的堆栈大小(就像在Ubuntu上一样)
答案 0 :(得分:0)
找到了问题的答案,pthread_attr_getstacksize
并不代表当前线程的堆栈大小。
我通过在堆栈上分配(使用alloca)内存并检查其是否真正正常工作来验证pthread_attr_setstacksize
是否工作正常。
更新的源代码如下,
#include <iostream>
#include <pthread.h>
#include <sys/time.h>
#include <sys/resource.h>
void* Function(void *ptr)
{
for ( int i = 1,count=1 ;;count++ ) {
size_t size = i * 1024 * 1024 ;
char *allocation = (char *)alloca(size);
allocation[0] = 1;
std::cout<<count<<std::endl;
}
return NULL;
}
int main ( int argc, char *argv[] )
{
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_t thread_id;
/* creating a new thread with thread stack size set */
pthread_create(&thread_id, &attr, &Function, NULL);
pthread_join(thread_id,0);
}