【问题标题】:My app mem usage is growing using pthread我的应用程序内存使用量正在使用 pthread 增长
【发布时间】: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


【解决方案1】:

当线程仍在运行/尚未启动时,您可能正在创建线程。这是未定义的行为。 (阅读:非常糟糕)

如果你修改你的程序做:

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
   pthread_join(&thread1, NULL);
   pthread_join(&thread2, NULL);
}

在开始新线程之前,您将等待线程完成。

请注意,每个线程都有自己的调用堆栈和控制结构,并且会消耗内存。最好限制应用程序中的线程数,并且不要快速创建和销毁线程。

【讨论】:

  • 我们的发明一跃而上! (参见驯悍记)。
【解决方案2】:

在循环创建新线程之前,确保当前线程已经完成:

while( 1 )
{
   pthread_create( &thread1, NULL, fthread1, NULL);
   pthread_create( &thread2, NULL, fthread2, NULL);
   pthread_join(&thread1);
   pthread_join(&thread2);
}

您创建线程的速度快于处理器清理它们的速度。

【讨论】:

    【解决方案3】:

    每个线程必须分离或连接。你不会分离你的线程,你不会分离地创建它们,也不会加入它们。您的 pthreads 实现必须永远保留线程,因为它无法知道您从未打算加入它们。

    【讨论】:

      猜你喜欢
      • 2010-10-08
      • 2013-11-02
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多