c - 使用 pthread 我的应用程序内存使用量正在增长

标签 c linux multithreading pthreads

我正在使用 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/

相关文章:

c++ - Qt:当你没有子类化 QThread 时如何清理它?

c++ - Boost thread_group 返回空矩阵(openCV)

c - 从单链表中删除节点的段错误

linux - 如何测量 Linux 中命令的 IOPS?

c++ - 不匹配的 C++ header 版本

linux - 通过 tar 将 Yocto Project 复制到其他 PC

Java - 在线程中的 while 循环后无法访问 StringBuilder

c - Linux : TCP socket programming over multiple ethernet ports

c - KdTree C 实现导致核心转储

c - 如何在套接字连接中接收 tcp 标志