我正在使用 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 的部分。我怎样才能让我的应用程序不使用太多内存。
最佳答案
您可能会在线程仍在运行/尚未启动时创建线程。这是未定义的行为。 (阅读:非常糟糕)
如果你修改你的程序来做:
while( 1 )
{
pthread_create( &thread1, NULL, fthread1, NULL);
pthread_create( &thread2, NULL, fthread2, NULL);
pthread_join(&thread1, NULL);
pthread_join(&thread2, NULL);
}
在开始新线程之前,您将等待线程完成。
注意每个线程都有自己的调用栈和控制结构,会消耗内存。最好限制应用程序中的线程数,并且不要快速创建和销毁线程。
关于c - 使用 pthread 我的应用程序内存使用量正在增长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098080/