【发布时间】:2010-06-23 00:09:49
【问题描述】:
我使用 C 语言和 Linux 作为我的编程平台。
在我的用户空间应用程序中。我使用 pthread 创建了一个线程。
int main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, fthread1, NULL );
pthread_create( &thread2, NULL, fthread2, NULL );
return 0;
}
void *fthread1( void *ptr )
{
/* do something here */
pthread_exit( NULL );
}
void *fthread2( void *ptr )
{
/* do something here */
pthread_exit( NULL );
}
我的问题是当我循环 pthread_create 以再次创建两个线程时,我的应用程序内存使用量越来越大。
while( 1 )
{
pthread_create( &thread1, NULL, fthread1, NULL);
pthread_create( &thread2, NULL, fthread2, NULL);
}
我使用 VSZ 列中的 Linux ps 命令行工具确定内存使用情况。
似乎我错过了使用 pthreads API 的部分内容。如何让我的应用不占用太多内存。
【问题讨论】:
-
您正在启动线程,每个线程都有自己的堆栈。为什么您不期望内存使用量增长?
-
但是如果线程已经完成了怎么办(pthread_exit)。它使用的堆栈应该被清除吗?
-
如果不知道自己在做什么以及为什么,很难知道正确的答案是什么。当然
while(1) pthread_create不是您的最佳选择。 :) 发布的答案提供了一种可能的解决方案。
标签: c linux multithreading pthreads