gpt4 book ai didi

c++ - pthread_attr_setstacksize 和 pthread_exit

转载 作者:行者123 更新时间:2023-11-30 19:45:18 27 4
gpt4 key购买 nike

我有一个关于在大约 64Mb RAM 的嵌入式系统中进行 C 并发编程的问题。特别是,我想减少线程使用的默认内存,所以我定义了:

pthread_attr_t attr_test;
size_t stacksize = 0x186A0; // 100Kbyte
pthread_attr_init(&attr_test);
pthread_attr_setdetachstate(&attr_test, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr_test, stacksize);

因此,当线程启动时,它仅使用 100Kbyte 的虚拟内存。但是当线程结束并调用pthread_exit时,进程使用的虚拟内存会迅速增加!......

为什么?我能做什么?

谢谢!

更新:

主题 ->

void *thread_test(void *arg1) {
int *param;
param = (int*)arg1;

printf("Thread %d start\n", *param);
pthread_cond_wait(&condition[*param], &mutex[*param]);
printf("Thread %d stop\n",*param);
pthread_exit(0);
}

主要 ->

int main(void) {
pthread_t IDthread[MAX_THREADS];
int param[MAX_THREADS];
int pointer;
int i, keyb;
void *stkaddr;
size_t stacksize;

puts("!!! THREAD TEST !!!");
printf("Process ID %d\n\n", getpid());

for(i=0; i<MAX_THREADS; i++)
{
pthread_cond_init(&condition[i], NULL);
pthread_mutex_init(&mutex[i], NULL);
IDthread[i] = 0;
param[i] = i;

}

stacksize = 0x186A0; // 100Kbyte

pthread_attr_init(&attr_test);

pthread_attr_setdetachstate(&attr_test, PTHREAD_CREATE_DETACHED);
/* setting the size of the stack also */
pthread_attr_setstacksize(&attr_test, stacksize);

pointer = 0;


do {
keyb = getchar();
if (keyb == '1')
{
if (pointer < MAX_THREADS)
{
pthread_create(&IDthread[pointer], &attr_test, thread_test, &param[pointer]);
sleep(1);
pointer++;
}
else
puts("MAX Threads Number");
}

if (keyb == '2')
{
if (pointer != 0)
{
pointer--;
pthread_cond_signal(&condition[pointer]);
sleep(1);
}
else
puts("0 Thread is running");
}

} while (keyb != '0');
printf("FINE\n");
return EXIT_SUCCESS;

}

最佳答案

可连接或分离线程存在一个已知问题,引用手册:

Only when a terminated joinable thread has been joined are the last of its resources released back to the system. When a detached thread terminates, its resources are automatically released back to the system

您可以使用以下方法使线程可拆卸:

pthread_attr_setdetachstate(3)

关于c++ - pthread_attr_setstacksize 和 pthread_exit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26590858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com